Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

DBconnect

Temple University IS&T Capstone Database Connection Library
Contact the Author @chorizo.burrito@temple.edu</br/>

OVERVIEW This Library is just one class. It fixes the issues with the previous Connection class as well adds some more functionality. You are free to use it and modify it as needed.

Content

Unique Constraint
Methods
User-Defined Table Parameters
SQL Merge Function
Search Stored Procedure

###Unique Constraint ####Notes: A Unique Constraint is similar to a primary key. The difference between the two is that a Unique Constraint is a unique identifier made up of two or more fields.

####Example: Set up a unquie constraint with a script:

CONSTRAINT [UC_NameOfConstraint] UNIQUE NONCLUSTERED ([college] ASC, [term] ASC)

This can be put at the bottom of your table script within the T-SQL tab in in Design view. Or you can right click Keys on the right side in the designer view and Add New > Unique Key.

	["CST", "Fall 2016"]
["CST", "Fall 2015"]
["ED", "Fall 2016"]
["ED", "Fall 2015"]

These records are all different. If you try to insert

	["CST", "Fall 2016"]

you will get an error.

###Methods ####Notes: The majority of the methods have not changed overall. The only change to all methods is that they call CloseConnection() at the end of the method now. Just to make sure that the database connection is actually close.

The new method is:

DoUpdateWithDSCmdOjb(DataSetpasseddataset,StringDBTableDestination)

The DBTableDestination is the name of the table to which you are inserting the data into. The dataset HAS to have the SAME COLUMN NAMES as the SQL table in the database.

The downsides to this method is that it does not handle duplicates. It will just push the data to the table. So if you have

["1", "Chips", "10"]
["3", "Dip", "20"]
["8", "Cookies", "15"]
["1", "Chips", "10"]

the first and last record (["1", "Chips", "10"]) will be added twice.

I would suggest using this method to initially populate your data.

###User-Defined Table Parameters ####Notes: This of a User-Defined Table as a data type for SQL. Once you create it you can call it in a stored procedure. For systems that need to do a database call for multiple records it makes it more efficent to use a User-Defined Table instead of making multiple calls. It is best to use them in conjunction with SQL Merge Functions (next section). A User-Defined Table will need to have some but not all of the same columns and types as the table you plan on using it with in your database. If columns allow null values or something that can be set within the stored procedure, like a time stamp, you do not need to as that column within the User-Defined Table Type.

####How to create them: When in your database in either Visual Studio 2012/2015 or Microsoft SQL Server Manager Studio go down to your Programmability folder. Within there open Types. Then right-click User-Defined Table Type. Click on the first option Add New User-Defined Table Type.... A script will open. As you will see the first line is CREATE TYPE [dbo].[UserDefinedTableType] AS TABLE. If you have ever made a table using a SQL script before this is very similar. A thing to keep in mind, as mentioned earlier, is to have the same types as the table you plan to use this user-defined-table with. Here is an example of what it will look like:

CREATE TYPE [dbo].[ExampleOfUserDefinedTable] AS TABLE
(
id (INT) NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
departmentID (INT) NOT NULL
)

The NOT NULL isn't required but it is a good practice to put them.

When using a User-Defined Table in a stored procedure all you will need to do is create the table within C#. You can attach the C# table to a SqlCommand object no problem. Example of this:

DataTablet=newDataTable();t.Columns.Add("id")
t.Columns.Add("first_name");t.Columns.Add("last_name");t.Columns.Add("departmentID");

The column names are the same as the user-defined-table that was created in the previous section. Doing so make it a lot easier following how the code works. Once the table is full of data you can add it as a parameter to a stored procedure.

publicstaticvoidMergeExample(DataTablet){DBConnectmyDB=newDBConnect();SqlCommandobjEx=newSqlCommand();objEx.CommandType=CommandType.StoreProcedure;ojbEx.CommandText="MergeExampleSP";objEx.Parameters.AddWithValue("@tableType",t);myDB.DoUpdateWithDSCmdOjb(objEx);myDB.CloseConnection();}

FOR THE LOVE OF GOD CLOSE ALL YOUR DATABASE CONNECTIONS!

###SQL Merge Function ####Notes: SQL Merge is a really powerful function. It can take data merge it into a table either by doing INSERT or doing an UPDATE.

Now this is the example of the what a stored procedure will look like. Look at the SQL code first before reading the explanation.

	ALTER PROCEDURE [dbo].[MergeExampleSP]
(
@tableType ExampleOfUserDefinedTable READONLY --The READONLY is required so the database knows it isn't doing anything except reading the table.
)
ASBEGIN
MERGE INTO dbo.FacultyAS m1 --m1 an alias for Faculty, this is the Target Table
USING @tblAccessRequests AS m2 --m2 is alias for the parameter, this is the Source TableONm1.id=m2.id--id is the primary key for Faculty
WHEN MATCHED THEN --If primary key matches between both tables UPDATE firesUPDATESETm1.first_name=m2.first_name,
m1.last_name=m2.last_name,
m1.creation_date= GETDATE(),
m1.last_modified= GETDATE()
WHEN NOT MATCHED BY TARGET THEN --If primary key does not match INSERT fires
INSERT (id, first_name, last_name, creation_date, last_modified)
VALUES (m2.id, m2.first_name, m2.last_name, GETDATE(), GETDATE()); --The ; ends the function
END

After MERGE INTO is the table within the database where the data is being merge into. The dbo. stands for DATABASE OWNER. It is required to make the MERGE function work. USING is telling the function what table is being used. The columns headers that were created in the User-Defined Table from the DataTable in C# are the same in SQL. The keyword ON is setting the primary key or unique constraint on which to use to identify a record within the table. If there is a match between that constraint between the target table and source table UPDATE will fire. This UPDATE takes the records from the source table and sets the target tables records to those values based on the constraint matched. The last two records set creation_date and last_modified are set by the systems current date. You could also set these values with whatever you want.

If the constraint between the target table and source table is not the same then the INSERT is fired. WHEN NOT MATCHED BY TARGET THEN means just that. If there is a record within the source table that is not within the target table it will now be inserted into the target table. Changing WHEN NOT MATCHED BY TARGET THEN is changed to WHEN NOT MATCHED BY SOURCE this will be changing something within the target table. If the code about was changed like that it would update all records that matched between the target table and the source table, insert any records present within the source table but not the target table, all records within the target table that are not present within the source table will be deleted. Syntax is important.

About

a repo of database functions

Resources

Stars

1 star

Watchers

6 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - TempleDev/DBconnect: a repo of database functions · GitHub
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

DBconnect

Temple University IS&T Capstone Database Connection Library
Contact the Author @chorizo.burrito@temple.edu</br/>

OVERVIEW This Library is just one class. It fixes the issues with the previous Connection class as well adds some more functionality. You are free to use it and modify it as needed.

Content

Unique Constraint
Methods
User-Defined Table Parameters
SQL Merge Function
Search Stored Procedure

###Unique Constraint ####Notes: A Unique Constraint is similar to a primary key. The difference between the two is that a Unique Constraint is a unique identifier made up of two or more fields.

####Example: Set up a unquie constraint with a script:

CONSTRAINT [UC_NameOfConstraint] UNIQUE NONCLUSTERED ([college] ASC, [term] ASC)

This can be put at the bottom of your table script within the T-SQL tab in in Design view. Or you can right click Keys on the right side in the designer view and Add New > Unique Key.

	["CST", "Fall 2016"]
["CST", "Fall 2015"]
["ED", "Fall 2016"]
["ED", "Fall 2015"]

These records are all different. If you try to insert

	["CST", "Fall 2016"]

you will get an error.

###Methods ####Notes: The majority of the methods have not changed overall. The only change to all methods is that they call CloseConnection() at the end of the method now. Just to make sure that the database connection is actually close.

The new method is:

DoUpdateWithDSCmdOjb(DataSetpasseddataset,StringDBTableDestination)

The DBTableDestination is the name of the table to which you are inserting the data into. The dataset HAS to have the SAME COLUMN NAMES as the SQL table in the database.

The downsides to this method is that it does not handle duplicates. It will just push the data to the table. So if you have

["1", "Chips", "10"]
["3", "Dip", "20"]
["8", "Cookies", "15"]
["1", "Chips", "10"]

the first and last record (["1", "Chips", "10"]) will be added twice.

I would suggest using this method to initially populate your data.

###User-Defined Table Parameters ####Notes: This of a User-Defined Table as a data type for SQL. Once you create it you can call it in a stored procedure. For systems that need to do a database call for multiple records it makes it more efficent to use a User-Defined Table instead of making multiple calls. It is best to use them in conjunction with SQL Merge Functions (next section). A User-Defined Table will need to have some but not all of the same columns and types as the table you plan on using it with in your database. If columns allow null values or something that can be set within the stored procedure, like a time stamp, you do not need to as that column within the User-Defined Table Type.

####How to create them: When in your database in either Visual Studio 2012/2015 or Microsoft SQL Server Manager Studio go down to your Programmability folder. Within there open Types. Then right-click User-Defined Table Type. Click on the first option Add New User-Defined Table Type.... A script will open. As you will see the first line is CREATE TYPE [dbo].[UserDefinedTableType] AS TABLE. If you have ever made a table using a SQL script before this is very similar. A thing to keep in mind, as mentioned earlier, is to have the same types as the table you plan to use this user-defined-table with. Here is an example of what it will look like:

CREATE TYPE [dbo].[ExampleOfUserDefinedTable] AS TABLE
(
id (INT) NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
departmentID (INT) NOT NULL
)

The NOT NULL isn't required but it is a good practice to put them.

When using a User-Defined Table in a stored procedure all you will need to do is create the table within C#. You can attach the C# table to a SqlCommand object no problem. Example of this:

DataTablet=newDataTable();t.Columns.Add("id")
t.Columns.Add("first_name");t.Columns.Add("last_name");t.Columns.Add("departmentID");

The column names are the same as the user-defined-table that was created in the previous section. Doing so make it a lot easier following how the code works. Once the table is full of data you can add it as a parameter to a stored procedure.

publicstaticvoidMergeExample(DataTablet){DBConnectmyDB=newDBConnect();SqlCommandobjEx=newSqlCommand();objEx.CommandType=CommandType.StoreProcedure;ojbEx.CommandText="MergeExampleSP";objEx.Parameters.AddWithValue("@tableType",t);myDB.DoUpdateWithDSCmdOjb(objEx);myDB.CloseConnection();}

FOR THE LOVE OF GOD CLOSE ALL YOUR DATABASE CONNECTIONS!

###SQL Merge Function ####Notes: SQL Merge is a really powerful function. It can take data merge it into a table either by doing INSERT or doing an UPDATE.

Now this is the example of the what a stored procedure will look like. Look at the SQL code first before reading the explanation.

	ALTER PROCEDURE [dbo].[MergeExampleSP]
(
@tableType ExampleOfUserDefinedTable READONLY --The READONLY is required so the database knows it isn't doing anything except reading the table.
)
ASBEGIN
MERGE INTO dbo.FacultyAS m1 --m1 an alias for Faculty, this is the Target Table
USING @tblAccessRequests AS m2 --m2 is alias for the parameter, this is the Source TableONm1.id=m2.id--id is the primary key for Faculty
WHEN MATCHED THEN --If primary key matches between both tables UPDATE firesUPDATESETm1.first_name=m2.first_name,
m1.last_name=m2.last_name,
m1.creation_date= GETDATE(),
m1.last_modified= GETDATE()
WHEN NOT MATCHED BY TARGET THEN --If primary key does not match INSERT fires
INSERT (id, first_name, last_name, creation_date, last_modified)
VALUES (m2.id, m2.first_name, m2.last_name, GETDATE(), GETDATE()); --The ; ends the function
END

After MERGE INTO is the table within the database where the data is being merge into. The dbo. stands for DATABASE OWNER. It is required to make the MERGE function work. USING is telling the function what table is being used. The columns headers that were created in the User-Defined Table from the DataTable in C# are the same in SQL. The keyword ON is setting the primary key or unique constraint on which to use to identify a record within the table. If there is a match between that constraint between the target table and source table UPDATE will fire. This UPDATE takes the records from the source table and sets the target tables records to those values based on the constraint matched. The last two records set creation_date and last_modified are set by the systems current date. You could also set these values with whatever you want.

If the constraint between the target table and source table is not the same then the INSERT is fired. WHEN NOT MATCHED BY TARGET THEN means just that. If there is a record within the source table that is not within the target table it will now be inserted into the target table. Changing WHEN NOT MATCHED BY TARGET THEN is changed to WHEN NOT MATCHED BY SOURCE this will be changing something within the target table. If the code about was changed like that it would update all records that matched between the target table and the source table, insert any records present within the source table but not the target table, all records within the target table that are not present within the source table will be deleted. Syntax is important.

About

a repo of database functions

Resources

Stars

1 star

Watchers

6 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - TempleDev/DBconnect: a repo of database functions · GitHub
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

DBconnect

Temple University IS&T Capstone Database Connection Library
Contact the Author @chorizo.burrito@temple.edu</br/>

OVERVIEW This Library is just one class. It fixes the issues with the previous Connection class as well adds some more functionality. You are free to use it and modify it as needed.

Content

Unique Constraint
Methods
User-Defined Table Parameters
SQL Merge Function
Search Stored Procedure

###Unique Constraint ####Notes: A Unique Constraint is similar to a primary key. The difference between the two is that a Unique Constraint is a unique identifier made up of two or more fields.

####Example: Set up a unquie constraint with a script:

CONSTRAINT [UC_NameOfConstraint] UNIQUE NONCLUSTERED ([college] ASC, [term] ASC)

This can be put at the bottom of your table script within the T-SQL tab in in Design view. Or you can right click Keys on the right side in the designer view and Add New > Unique Key.

	["CST", "Fall 2016"]
["CST", "Fall 2015"]
["ED", "Fall 2016"]
["ED", "Fall 2015"]

These records are all different. If you try to insert

	["CST", "Fall 2016"]

you will get an error.

###Methods ####Notes: The majority of the methods have not changed overall. The only change to all methods is that they call CloseConnection() at the end of the method now. Just to make sure that the database connection is actually close.

The new method is:

DoUpdateWithDSCmdOjb(DataSetpasseddataset,StringDBTableDestination)

The DBTableDestination is the name of the table to which you are inserting the data into. The dataset HAS to have the SAME COLUMN NAMES as the SQL table in the database.

The downsides to this method is that it does not handle duplicates. It will just push the data to the table. So if you have

["1", "Chips", "10"]
["3", "Dip", "20"]
["8", "Cookies", "15"]
["1", "Chips", "10"]

the first and last record (["1", "Chips", "10"]) will be added twice.

I would suggest using this method to initially populate your data.

###User-Defined Table Parameters ####Notes: This of a User-Defined Table as a data type for SQL. Once you create it you can call it in a stored procedure. For systems that need to do a database call for multiple records it makes it more efficent to use a User-Defined Table instead of making multiple calls. It is best to use them in conjunction with SQL Merge Functions (next section). A User-Defined Table will need to have some but not all of the same columns and types as the table you plan on using it with in your database. If columns allow null values or something that can be set within the stored procedure, like a time stamp, you do not need to as that column within the User-Defined Table Type.

####How to create them: When in your database in either Visual Studio 2012/2015 or Microsoft SQL Server Manager Studio go down to your Programmability folder. Within there open Types. Then right-click User-Defined Table Type. Click on the first option Add New User-Defined Table Type.... A script will open. As you will see the first line is CREATE TYPE [dbo].[UserDefinedTableType] AS TABLE. If you have ever made a table using a SQL script before this is very similar. A thing to keep in mind, as mentioned earlier, is to have the same types as the table you plan to use this user-defined-table with. Here is an example of what it will look like:

CREATE TYPE [dbo].[ExampleOfUserDefinedTable] AS TABLE
(
id (INT) NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
departmentID (INT) NOT NULL
)

The NOT NULL isn't required but it is a good practice to put them.

When using a User-Defined Table in a stored procedure all you will need to do is create the table within C#. You can attach the C# table to a SqlCommand object no problem. Example of this:

DataTablet=newDataTable();t.Columns.Add("id")
t.Columns.Add("first_name");t.Columns.Add("last_name");t.Columns.Add("departmentID");

The column names are the same as the user-defined-table that was created in the previous section. Doing so make it a lot easier following how the code works. Once the table is full of data you can add it as a parameter to a stored procedure.

publicstaticvoidMergeExample(DataTablet){DBConnectmyDB=newDBConnect();SqlCommandobjEx=newSqlCommand();objEx.CommandType=CommandType.StoreProcedure;ojbEx.CommandText="MergeExampleSP";objEx.Parameters.AddWithValue("@tableType",t);myDB.DoUpdateWithDSCmdOjb(objEx);myDB.CloseConnection();}

FOR THE LOVE OF GOD CLOSE ALL YOUR DATABASE CONNECTIONS!

###SQL Merge Function ####Notes: SQL Merge is a really powerful function. It can take data merge it into a table either by doing INSERT or doing an UPDATE.

Now this is the example of the what a stored procedure will look like. Look at the SQL code first before reading the explanation.

	ALTER PROCEDURE [dbo].[MergeExampleSP]
(
@tableType ExampleOfUserDefinedTable READONLY --The READONLY is required so the database knows it isn't doing anything except reading the table.
)
ASBEGIN
MERGE INTO dbo.FacultyAS m1 --m1 an alias for Faculty, this is the Target Table
USING @tblAccessRequests AS m2 --m2 is alias for the parameter, this is the Source TableONm1.id=m2.id--id is the primary key for Faculty
WHEN MATCHED THEN --If primary key matches between both tables UPDATE firesUPDATESETm1.first_name=m2.first_name,
m1.last_name=m2.last_name,
m1.creation_date= GETDATE(),
m1.last_modified= GETDATE()
WHEN NOT MATCHED BY TARGET THEN --If primary key does not match INSERT fires
INSERT (id, first_name, last_name, creation_date, last_modified)
VALUES (m2.id, m2.first_name, m2.last_name, GETDATE(), GETDATE()); --The ; ends the function
END

After MERGE INTO is the table within the database where the data is being merge into. The dbo. stands for DATABASE OWNER. It is required to make the MERGE function work. USING is telling the function what table is being used. The columns headers that were created in the User-Defined Table from the DataTable in C# are the same in SQL. The keyword ON is setting the primary key or unique constraint on which to use to identify a record within the table. If there is a match between that constraint between the target table and source table UPDATE will fire. This UPDATE takes the records from the source table and sets the target tables records to those values based on the constraint matched. The last two records set creation_date and last_modified are set by the systems current date. You could also set these values with whatever you want.

If the constraint between the target table and source table is not the same then the INSERT is fired. WHEN NOT MATCHED BY TARGET THEN means just that. If there is a record within the source table that is not within the target table it will now be inserted into the target table. Changing WHEN NOT MATCHED BY TARGET THEN is changed to WHEN NOT MATCHED BY SOURCE this will be changing something within the target table. If the code about was changed like that it would update all records that matched between the target table and the source table, insert any records present within the source table but not the target table, all records within the target table that are not present within the source table will be deleted. Syntax is important.

About

a repo of database functions

Resources

Stars

1 star

Watchers

6 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - TempleDev/DBconnect: a repo of database functions · GitHub
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

DBconnect

Temple University IS&T Capstone Database Connection Library
Contact the Author @chorizo.burrito@temple.edu</br/>

OVERVIEW This Library is just one class. It fixes the issues with the previous Connection class as well adds some more functionality. You are free to use it and modify it as needed.

Content

Unique Constraint
Methods
User-Defined Table Parameters
SQL Merge Function
Search Stored Procedure

###Unique Constraint ####Notes: A Unique Constraint is similar to a primary key. The difference between the two is that a Unique Constraint is a unique identifier made up of two or more fields.

####Example: Set up a unquie constraint with a script:

CONSTRAINT [UC_NameOfConstraint] UNIQUE NONCLUSTERED ([college] ASC, [term] ASC)

This can be put at the bottom of your table script within the T-SQL tab in in Design view. Or you can right click Keys on the right side in the designer view and Add New > Unique Key.

	["CST", "Fall 2016"]
["CST", "Fall 2015"]
["ED", "Fall 2016"]
["ED", "Fall 2015"]

These records are all different. If you try to insert

	["CST", "Fall 2016"]

you will get an error.

###Methods ####Notes: The majority of the methods have not changed overall. The only change to all methods is that they call CloseConnection() at the end of the method now. Just to make sure that the database connection is actually close.

The new method is:

DoUpdateWithDSCmdOjb(DataSetpasseddataset,StringDBTableDestination)

The DBTableDestination is the name of the table to which you are inserting the data into. The dataset HAS to have the SAME COLUMN NAMES as the SQL table in the database.

The downsides to this method is that it does not handle duplicates. It will just push the data to the table. So if you have

["1", "Chips", "10"]
["3", "Dip", "20"]
["8", "Cookies", "15"]
["1", "Chips", "10"]

the first and last record (["1", "Chips", "10"]) will be added twice.

I would suggest using this method to initially populate your data.

###User-Defined Table Parameters ####Notes: This of a User-Defined Table as a data type for SQL. Once you create it you can call it in a stored procedure. For systems that need to do a database call for multiple records it makes it more efficent to use a User-Defined Table instead of making multiple calls. It is best to use them in conjunction with SQL Merge Functions (next section). A User-Defined Table will need to have some but not all of the same columns and types as the table you plan on using it with in your database. If columns allow null values or something that can be set within the stored procedure, like a time stamp, you do not need to as that column within the User-Defined Table Type.

####How to create them: When in your database in either Visual Studio 2012/2015 or Microsoft SQL Server Manager Studio go down to your Programmability folder. Within there open Types. Then right-click User-Defined Table Type. Click on the first option Add New User-Defined Table Type.... A script will open. As you will see the first line is CREATE TYPE [dbo].[UserDefinedTableType] AS TABLE. If you have ever made a table using a SQL script before this is very similar. A thing to keep in mind, as mentioned earlier, is to have the same types as the table you plan to use this user-defined-table with. Here is an example of what it will look like:

CREATE TYPE [dbo].[ExampleOfUserDefinedTable] AS TABLE
(
id (INT) NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
departmentID (INT) NOT NULL
)

The NOT NULL isn't required but it is a good practice to put them.

When using a User-Defined Table in a stored procedure all you will need to do is create the table within C#. You can attach the C# table to a SqlCommand object no problem. Example of this:

DataTablet=newDataTable();t.Columns.Add("id")
t.Columns.Add("first_name");t.Columns.Add("last_name");t.Columns.Add("departmentID");

The column names are the same as the user-defined-table that was created in the previous section. Doing so make it a lot easier following how the code works. Once the table is full of data you can add it as a parameter to a stored procedure.

publicstaticvoidMergeExample(DataTablet){DBConnectmyDB=newDBConnect();SqlCommandobjEx=newSqlCommand();objEx.CommandType=CommandType.StoreProcedure;ojbEx.CommandText="MergeExampleSP";objEx.Parameters.AddWithValue("@tableType",t);myDB.DoUpdateWithDSCmdOjb(objEx);myDB.CloseConnection();}

FOR THE LOVE OF GOD CLOSE ALL YOUR DATABASE CONNECTIONS!

###SQL Merge Function ####Notes: SQL Merge is a really powerful function. It can take data merge it into a table either by doing INSERT or doing an UPDATE.

Now this is the example of the what a stored procedure will look like. Look at the SQL code first before reading the explanation.

	ALTER PROCEDURE [dbo].[MergeExampleSP]
(
@tableType ExampleOfUserDefinedTable READONLY --The READONLY is required so the database knows it isn't doing anything except reading the table.
)
ASBEGIN
MERGE INTO dbo.FacultyAS m1 --m1 an alias for Faculty, this is the Target Table
USING @tblAccessRequests AS m2 --m2 is alias for the parameter, this is the Source TableONm1.id=m2.id--id is the primary key for Faculty
WHEN MATCHED THEN --If primary key matches between both tables UPDATE firesUPDATESETm1.first_name=m2.first_name,
m1.last_name=m2.last_name,
m1.creation_date= GETDATE(),
m1.last_modified= GETDATE()
WHEN NOT MATCHED BY TARGET THEN --If primary key does not match INSERT fires
INSERT (id, first_name, last_name, creation_date, last_modified)
VALUES (m2.id, m2.first_name, m2.last_name, GETDATE(), GETDATE()); --The ; ends the function
END

After MERGE INTO is the table within the database where the data is being merge into. The dbo. stands for DATABASE OWNER. It is required to make the MERGE function work. USING is telling the function what table is being used. The columns headers that were created in the User-Defined Table from the DataTable in C# are the same in SQL. The keyword ON is setting the primary key or unique constraint on which to use to identify a record within the table. If there is a match between that constraint between the target table and source table UPDATE will fire. This UPDATE takes the records from the source table and sets the target tables records to those values based on the constraint matched. The last two records set creation_date and last_modified are set by the systems current date. You could also set these values with whatever you want.

If the constraint between the target table and source table is not the same then the INSERT is fired. WHEN NOT MATCHED BY TARGET THEN means just that. If there is a record within the source table that is not within the target table it will now be inserted into the target table. Changing WHEN NOT MATCHED BY TARGET THEN is changed to WHEN NOT MATCHED BY SOURCE this will be changing something within the target table. If the code about was changed like that it would update all records that matched between the target table and the source table, insert any records present within the source table but not the target table, all records within the target table that are not present within the source table will be deleted. Syntax is important.

About

a repo of database functions

Resources

Stars

1 star

Watchers

6 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - TempleDev/DBconnect: a repo of database functions · GitHub
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

DBconnect

Temple University IS&T Capstone Database Connection Library
Contact the Author @chorizo.burrito@temple.edu</br/>

OVERVIEW This Library is just one class. It fixes the issues with the previous Connection class as well adds some more functionality. You are free to use it and modify it as needed.

Content

Unique Constraint
Methods
User-Defined Table Parameters
SQL Merge Function
Search Stored Procedure

###Unique Constraint ####Notes: A Unique Constraint is similar to a primary key. The difference between the two is that a Unique Constraint is a unique identifier made up of two or more fields.

####Example: Set up a unquie constraint with a script:

CONSTRAINT [UC_NameOfConstraint] UNIQUE NONCLUSTERED ([college] ASC, [term] ASC)

This can be put at the bottom of your table script within the T-SQL tab in in Design view. Or you can right click Keys on the right side in the designer view and Add New > Unique Key.

	["CST", "Fall 2016"]
["CST", "Fall 2015"]
["ED", "Fall 2016"]
["ED", "Fall 2015"]

These records are all different. If you try to insert

	["CST", "Fall 2016"]

you will get an error.

###Methods ####Notes: The majority of the methods have not changed overall. The only change to all methods is that they call CloseConnection() at the end of the method now. Just to make sure that the database connection is actually close.

The new method is:

DoUpdateWithDSCmdOjb(DataSetpasseddataset,StringDBTableDestination)

The DBTableDestination is the name of the table to which you are inserting the data into. The dataset HAS to have the SAME COLUMN NAMES as the SQL table in the database.

The downsides to this method is that it does not handle duplicates. It will just push the data to the table. So if you have

["1", "Chips", "10"]
["3", "Dip", "20"]
["8", "Cookies", "15"]
["1", "Chips", "10"]

the first and last record (["1", "Chips", "10"]) will be added twice.

I would suggest using this method to initially populate your data.

###User-Defined Table Parameters ####Notes: This of a User-Defined Table as a data type for SQL. Once you create it you can call it in a stored procedure. For systems that need to do a database call for multiple records it makes it more efficent to use a User-Defined Table instead of making multiple calls. It is best to use them in conjunction with SQL Merge Functions (next section). A User-Defined Table will need to have some but not all of the same columns and types as the table you plan on using it with in your database. If columns allow null values or something that can be set within the stored procedure, like a time stamp, you do not need to as that column within the User-Defined Table Type.

####How to create them: When in your database in either Visual Studio 2012/2015 or Microsoft SQL Server Manager Studio go down to your Programmability folder. Within there open Types. Then right-click User-Defined Table Type. Click on the first option Add New User-Defined Table Type.... A script will open. As you will see the first line is CREATE TYPE [dbo].[UserDefinedTableType] AS TABLE. If you have ever made a table using a SQL script before this is very similar. A thing to keep in mind, as mentioned earlier, is to have the same types as the table you plan to use this user-defined-table with. Here is an example of what it will look like:

CREATE TYPE [dbo].[ExampleOfUserDefinedTable] AS TABLE
(
id (INT) NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
departmentID (INT) NOT NULL
)

The NOT NULL isn't required but it is a good practice to put them.

When using a User-Defined Table in a stored procedure all you will need to do is create the table within C#. You can attach the C# table to a SqlCommand object no problem. Example of this:

DataTablet=newDataTable();t.Columns.Add("id")
t.Columns.Add("first_name");t.Columns.Add("last_name");t.Columns.Add("departmentID");

The column names are the same as the user-defined-table that was created in the previous section. Doing so make it a lot easier following how the code works. Once the table is full of data you can add it as a parameter to a stored procedure.

publicstaticvoidMergeExample(DataTablet){DBConnectmyDB=newDBConnect();SqlCommandobjEx=newSqlCommand();objEx.CommandType=CommandType.StoreProcedure;ojbEx.CommandText="MergeExampleSP";objEx.Parameters.AddWithValue("@tableType",t);myDB.DoUpdateWithDSCmdOjb(objEx);myDB.CloseConnection();}

FOR THE LOVE OF GOD CLOSE ALL YOUR DATABASE CONNECTIONS!

###SQL Merge Function ####Notes: SQL Merge is a really powerful function. It can take data merge it into a table either by doing INSERT or doing an UPDATE.

Now this is the example of the what a stored procedure will look like. Look at the SQL code first before reading the explanation.

	ALTER PROCEDURE [dbo].[MergeExampleSP]
(
@tableType ExampleOfUserDefinedTable READONLY --The READONLY is required so the database knows it isn't doing anything except reading the table.
)
ASBEGIN
MERGE INTO dbo.FacultyAS m1 --m1 an alias for Faculty, this is the Target Table
USING @tblAccessRequests AS m2 --m2 is alias for the parameter, this is the Source TableONm1.id=m2.id--id is the primary key for Faculty
WHEN MATCHED THEN --If primary key matches between both tables UPDATE firesUPDATESETm1.first_name=m2.first_name,
m1.last_name=m2.last_name,
m1.creation_date= GETDATE(),
m1.last_modified= GETDATE()
WHEN NOT MATCHED BY TARGET THEN --If primary key does not match INSERT fires
INSERT (id, first_name, last_name, creation_date, last_modified)
VALUES (m2.id, m2.first_name, m2.last_name, GETDATE(), GETDATE()); --The ; ends the function
END

After MERGE INTO is the table within the database where the data is being merge into. The dbo. stands for DATABASE OWNER. It is required to make the MERGE function work. USING is telling the function what table is being used. The columns headers that were created in the User-Defined Table from the DataTable in C# are the same in SQL. The keyword ON is setting the primary key or unique constraint on which to use to identify a record within the table. If there is a match between that constraint between the target table and source table UPDATE will fire. This UPDATE takes the records from the source table and sets the target tables records to those values based on the constraint matched. The last two records set creation_date and last_modified are set by the systems current date. You could also set these values with whatever you want.

If the constraint between the target table and source table is not the same then the INSERT is fired. WHEN NOT MATCHED BY TARGET THEN means just that. If there is a record within the source table that is not within the target table it will now be inserted into the target table. Changing WHEN NOT MATCHED BY TARGET THEN is changed to WHEN NOT MATCHED BY SOURCE this will be changing something within the target table. If the code about was changed like that it would update all records that matched between the target table and the source table, insert any records present within the source table but not the target table, all records within the target table that are not present within the source table will be deleted. Syntax is important.

About

a repo of database functions

Resources

Stars

1 star

Watchers

6 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - TempleDev/DBconnect: a repo of database functions · GitHub
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

DBconnect

Temple University IS&T Capstone Database Connection Library
Contact the Author @chorizo.burrito@temple.edu</br/>

OVERVIEW This Library is just one class. It fixes the issues with the previous Connection class as well adds some more functionality. You are free to use it and modify it as needed.

Content

Unique Constraint
Methods
User-Defined Table Parameters
SQL Merge Function
Search Stored Procedure

###Unique Constraint ####Notes: A Unique Constraint is similar to a primary key. The difference between the two is that a Unique Constraint is a unique identifier made up of two or more fields.

####Example: Set up a unquie constraint with a script:

CONSTRAINT [UC_NameOfConstraint] UNIQUE NONCLUSTERED ([college] ASC, [term] ASC)

This can be put at the bottom of your table script within the T-SQL tab in in Design view. Or you can right click Keys on the right side in the designer view and Add New > Unique Key.

	["CST", "Fall 2016"]
["CST", "Fall 2015"]
["ED", "Fall 2016"]
["ED", "Fall 2015"]

These records are all different. If you try to insert

	["CST", "Fall 2016"]

you will get an error.

###Methods ####Notes: The majority of the methods have not changed overall. The only change to all methods is that they call CloseConnection() at the end of the method now. Just to make sure that the database connection is actually close.

The new method is:

DoUpdateWithDSCmdOjb(DataSetpasseddataset,StringDBTableDestination)

The DBTableDestination is the name of the table to which you are inserting the data into. The dataset HAS to have the SAME COLUMN NAMES as the SQL table in the database.

The downsides to this method is that it does not handle duplicates. It will just push the data to the table. So if you have

["1", "Chips", "10"]
["3", "Dip", "20"]
["8", "Cookies", "15"]
["1", "Chips", "10"]

the first and last record (["1", "Chips", "10"]) will be added twice.

I would suggest using this method to initially populate your data.

###User-Defined Table Parameters ####Notes: This of a User-Defined Table as a data type for SQL. Once you create it you can call it in a stored procedure. For systems that need to do a database call for multiple records it makes it more efficent to use a User-Defined Table instead of making multiple calls. It is best to use them in conjunction with SQL Merge Functions (next section). A User-Defined Table will need to have some but not all of the same columns and types as the table you plan on using it with in your database. If columns allow null values or something that can be set within the stored procedure, like a time stamp, you do not need to as that column within the User-Defined Table Type.

####How to create them: When in your database in either Visual Studio 2012/2015 or Microsoft SQL Server Manager Studio go down to your Programmability folder. Within there open Types. Then right-click User-Defined Table Type. Click on the first option Add New User-Defined Table Type.... A script will open. As you will see the first line is CREATE TYPE [dbo].[UserDefinedTableType] AS TABLE. If you have ever made a table using a SQL script before this is very similar. A thing to keep in mind, as mentioned earlier, is to have the same types as the table you plan to use this user-defined-table with. Here is an example of what it will look like:

CREATE TYPE [dbo].[ExampleOfUserDefinedTable] AS TABLE
(
id (INT) NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
departmentID (INT) NOT NULL
)

The NOT NULL isn't required but it is a good practice to put them.

When using a User-Defined Table in a stored procedure all you will need to do is create the table within C#. You can attach the C# table to a SqlCommand object no problem. Example of this:

DataTablet=newDataTable();t.Columns.Add("id")
t.Columns.Add("first_name");t.Columns.Add("last_name");t.Columns.Add("departmentID");

The column names are the same as the user-defined-table that was created in the previous section. Doing so make it a lot easier following how the code works. Once the table is full of data you can add it as a parameter to a stored procedure.

publicstaticvoidMergeExample(DataTablet){DBConnectmyDB=newDBConnect();SqlCommandobjEx=newSqlCommand();objEx.CommandType=CommandType.StoreProcedure;ojbEx.CommandText="MergeExampleSP";objEx.Parameters.AddWithValue("@tableType",t);myDB.DoUpdateWithDSCmdOjb(objEx);myDB.CloseConnection();}

FOR THE LOVE OF GOD CLOSE ALL YOUR DATABASE CONNECTIONS!

###SQL Merge Function ####Notes: SQL Merge is a really powerful function. It can take data merge it into a table either by doing INSERT or doing an UPDATE.

Now this is the example of the what a stored procedure will look like. Look at the SQL code first before reading the explanation.

	ALTER PROCEDURE [dbo].[MergeExampleSP]
(
@tableType ExampleOfUserDefinedTable READONLY --The READONLY is required so the database knows it isn't doing anything except reading the table.
)
ASBEGIN
MERGE INTO dbo.FacultyAS m1 --m1 an alias for Faculty, this is the Target Table
USING @tblAccessRequests AS m2 --m2 is alias for the parameter, this is the Source TableONm1.id=m2.id--id is the primary key for Faculty
WHEN MATCHED THEN --If primary key matches between both tables UPDATE firesUPDATESETm1.first_name=m2.first_name,
m1.last_name=m2.last_name,
m1.creation_date= GETDATE(),
m1.last_modified= GETDATE()
WHEN NOT MATCHED BY TARGET THEN --If primary key does not match INSERT fires
INSERT (id, first_name, last_name, creation_date, last_modified)
VALUES (m2.id, m2.first_name, m2.last_name, GETDATE(), GETDATE()); --The ; ends the function
END

After MERGE INTO is the table within the database where the data is being merge into. The dbo. stands for DATABASE OWNER. It is required to make the MERGE function work. USING is telling the function what table is being used. The columns headers that were created in the User-Defined Table from the DataTable in C# are the same in SQL. The keyword ON is setting the primary key or unique constraint on which to use to identify a record within the table. If there is a match between that constraint between the target table and source table UPDATE will fire. This UPDATE takes the records from the source table and sets the target tables records to those values based on the constraint matched. The last two records set creation_date and last_modified are set by the systems current date. You could also set these values with whatever you want.

If the constraint between the target table and source table is not the same then the INSERT is fired. WHEN NOT MATCHED BY TARGET THEN means just that. If there is a record within the source table that is not within the target table it will now be inserted into the target table. Changing WHEN NOT MATCHED BY TARGET THEN is changed to WHEN NOT MATCHED BY SOURCE this will be changing something within the target table. If the code about was changed like that it would update all records that matched between the target table and the source table, insert any records present within the source table but not the target table, all records within the target table that are not present within the source table will be deleted. Syntax is important.

About

a repo of database functions

Resources

Stars

1 star

Watchers

6 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - TempleDev/DBconnect: a repo of database functions · GitHub
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

DBconnect

Temple University IS&T Capstone Database Connection Library
Contact the Author @chorizo.burrito@temple.edu</br/>

OVERVIEW This Library is just one class. It fixes the issues with the previous Connection class as well adds some more functionality. You are free to use it and modify it as needed.

Content

Unique Constraint
Methods
User-Defined Table Parameters
SQL Merge Function
Search Stored Procedure

###Unique Constraint ####Notes: A Unique Constraint is similar to a primary key. The difference between the two is that a Unique Constraint is a unique identifier made up of two or more fields.

####Example: Set up a unquie constraint with a script:

CONSTRAINT [UC_NameOfConstraint] UNIQUE NONCLUSTERED ([college] ASC, [term] ASC)

This can be put at the bottom of your table script within the T-SQL tab in in Design view. Or you can right click Keys on the right side in the designer view and Add New > Unique Key.

	["CST", "Fall 2016"]
["CST", "Fall 2015"]
["ED", "Fall 2016"]
["ED", "Fall 2015"]

These records are all different. If you try to insert

	["CST", "Fall 2016"]

you will get an error.

###Methods ####Notes: The majority of the methods have not changed overall. The only change to all methods is that they call CloseConnection() at the end of the method now. Just to make sure that the database connection is actually close.

The new method is:

DoUpdateWithDSCmdOjb(DataSetpasseddataset,StringDBTableDestination)

The DBTableDestination is the name of the table to which you are inserting the data into. The dataset HAS to have the SAME COLUMN NAMES as the SQL table in the database.

The downsides to this method is that it does not handle duplicates. It will just push the data to the table. So if you have

["1", "Chips", "10"]
["3", "Dip", "20"]
["8", "Cookies", "15"]
["1", "Chips", "10"]

the first and last record (["1", "Chips", "10"]) will be added twice.

I would suggest using this method to initially populate your data.

###User-Defined Table Parameters ####Notes: This of a User-Defined Table as a data type for SQL. Once you create it you can call it in a stored procedure. For systems that need to do a database call for multiple records it makes it more efficent to use a User-Defined Table instead of making multiple calls. It is best to use them in conjunction with SQL Merge Functions (next section). A User-Defined Table will need to have some but not all of the same columns and types as the table you plan on using it with in your database. If columns allow null values or something that can be set within the stored procedure, like a time stamp, you do not need to as that column within the User-Defined Table Type.

####How to create them: When in your database in either Visual Studio 2012/2015 or Microsoft SQL Server Manager Studio go down to your Programmability folder. Within there open Types. Then right-click User-Defined Table Type. Click on the first option Add New User-Defined Table Type.... A script will open. As you will see the first line is CREATE TYPE [dbo].[UserDefinedTableType] AS TABLE. If you have ever made a table using a SQL script before this is very similar. A thing to keep in mind, as mentioned earlier, is to have the same types as the table you plan to use this user-defined-table with. Here is an example of what it will look like:

CREATE TYPE [dbo].[ExampleOfUserDefinedTable] AS TABLE
(
id (INT) NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
departmentID (INT) NOT NULL
)

The NOT NULL isn't required but it is a good practice to put them.

When using a User-Defined Table in a stored procedure all you will need to do is create the table within C#. You can attach the C# table to a SqlCommand object no problem. Example of this:

DataTablet=newDataTable();t.Columns.Add("id")
t.Columns.Add("first_name");t.Columns.Add("last_name");t.Columns.Add("departmentID");

The column names are the same as the user-defined-table that was created in the previous section. Doing so make it a lot easier following how the code works. Once the table is full of data you can add it as a parameter to a stored procedure.

publicstaticvoidMergeExample(DataTablet){DBConnectmyDB=newDBConnect();SqlCommandobjEx=newSqlCommand();objEx.CommandType=CommandType.StoreProcedure;ojbEx.CommandText="MergeExampleSP";objEx.Parameters.AddWithValue("@tableType",t);myDB.DoUpdateWithDSCmdOjb(objEx);myDB.CloseConnection();}

FOR THE LOVE OF GOD CLOSE ALL YOUR DATABASE CONNECTIONS!

###SQL Merge Function ####Notes: SQL Merge is a really powerful function. It can take data merge it into a table either by doing INSERT or doing an UPDATE.

Now this is the example of the what a stored procedure will look like. Look at the SQL code first before reading the explanation.

	ALTER PROCEDURE [dbo].[MergeExampleSP]
(
@tableType ExampleOfUserDefinedTable READONLY --The READONLY is required so the database knows it isn't doing anything except reading the table.
)
ASBEGIN
MERGE INTO dbo.FacultyAS m1 --m1 an alias for Faculty, this is the Target Table
USING @tblAccessRequests AS m2 --m2 is alias for the parameter, this is the Source TableONm1.id=m2.id--id is the primary key for Faculty
WHEN MATCHED THEN --If primary key matches between both tables UPDATE firesUPDATESETm1.first_name=m2.first_name,
m1.last_name=m2.last_name,
m1.creation_date= GETDATE(),
m1.last_modified= GETDATE()
WHEN NOT MATCHED BY TARGET THEN --If primary key does not match INSERT fires
INSERT (id, first_name, last_name, creation_date, last_modified)
VALUES (m2.id, m2.first_name, m2.last_name, GETDATE(), GETDATE()); --The ; ends the function
END

After MERGE INTO is the table within the database where the data is being merge into. The dbo. stands for DATABASE OWNER. It is required to make the MERGE function work. USING is telling the function what table is being used. The columns headers that were created in the User-Defined Table from the DataTable in C# are the same in SQL. The keyword ON is setting the primary key or unique constraint on which to use to identify a record within the table. If there is a match between that constraint between the target table and source table UPDATE will fire. This UPDATE takes the records from the source table and sets the target tables records to those values based on the constraint matched. The last two records set creation_date and last_modified are set by the systems current date. You could also set these values with whatever you want.

If the constraint between the target table and source table is not the same then the INSERT is fired. WHEN NOT MATCHED BY TARGET THEN means just that. If there is a record within the source table that is not within the target table it will now be inserted into the target table. Changing WHEN NOT MATCHED BY TARGET THEN is changed to WHEN NOT MATCHED BY SOURCE this will be changing something within the target table. If the code about was changed like that it would update all records that matched between the target table and the source table, insert any records present within the source table but not the target table, all records within the target table that are not present within the source table will be deleted. Syntax is important.

About

a repo of database functions

Resources

Stars

1 star

Watchers

6 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - TempleDev/DBconnect: a repo of database functions · GitHub
Skip to content

Latest commit

History

12 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

DBconnect

Temple University IS&T Capstone Database Connection Library
Contact the Author @chorizo.burrito@temple.edu</br/>

OVERVIEW This Library is just one class. It fixes the issues with the previous Connection class as well adds some more functionality. You are free to use it and modify it as needed.

Content

Unique Constraint
Methods
User-Defined Table Parameters
SQL Merge Function
Search Stored Procedure

###Unique Constraint ####Notes: A Unique Constraint is similar to a primary key. The difference between the two is that a Unique Constraint is a unique identifier made up of two or more fields.

####Example: Set up a unquie constraint with a script:

CONSTRAINT [UC_NameOfConstraint] UNIQUE NONCLUSTERED ([college] ASC, [term] ASC)

This can be put at the bottom of your table script within the T-SQL tab in in Design view. Or you can right click Keys on the right side in the designer view and Add New > Unique Key.

	["CST", "Fall 2016"]
["CST", "Fall 2015"]
["ED", "Fall 2016"]
["ED", "Fall 2015"]

These records are all different. If you try to insert

	["CST", "Fall 2016"]

you will get an error.

###Methods ####Notes: The majority of the methods have not changed overall. The only change to all methods is that they call CloseConnection() at the end of the method now. Just to make sure that the database connection is actually close.

The new method is:

DoUpdateWithDSCmdOjb(DataSetpasseddataset,StringDBTableDestination)

The DBTableDestination is the name of the table to which you are inserting the data into. The dataset HAS to have the SAME COLUMN NAMES as the SQL table in the database.

The downsides to this method is that it does not handle duplicates. It will just push the data to the table. So if you have

["1", "Chips", "10"]
["3", "Dip", "20"]
["8", "Cookies", "15"]
["1", "Chips", "10"]

the first and last record (["1", "Chips", "10"]) will be added twice.

I would suggest using this method to initially populate your data.

###User-Defined Table Parameters ####Notes: This of a User-Defined Table as a data type for SQL. Once you create it you can call it in a stored procedure. For systems that need to do a database call for multiple records it makes it more efficent to use a User-Defined Table instead of making multiple calls. It is best to use them in conjunction with SQL Merge Functions (next section). A User-Defined Table will need to have some but not all of the same columns and types as the table you plan on using it with in your database. If columns allow null values or something that can be set within the stored procedure, like a time stamp, you do not need to as that column within the User-Defined Table Type.

####How to create them: When in your database in either Visual Studio 2012/2015 or Microsoft SQL Server Manager Studio go down to your Programmability folder. Within there open Types. Then right-click User-Defined Table Type. Click on the first option Add New User-Defined Table Type.... A script will open. As you will see the first line is CREATE TYPE [dbo].[UserDefinedTableType] AS TABLE. If you have ever made a table using a SQL script before this is very similar. A thing to keep in mind, as mentioned earlier, is to have the same types as the table you plan to use this user-defined-table with. Here is an example of what it will look like:

CREATE TYPE [dbo].[ExampleOfUserDefinedTable] AS TABLE
(
id (INT) NOT NULL,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
departmentID (INT) NOT NULL
)

The NOT NULL isn't required but it is a good practice to put them.

When using a User-Defined Table in a stored procedure all you will need to do is create the table within C#. You can attach the C# table to a SqlCommand object no problem. Example of this:

DataTablet=newDataTable();t.Columns.Add("id")
t.Columns.Add("first_name");t.Columns.Add("last_name");t.Columns.Add("departmentID");

The column names are the same as the user-defined-table that was created in the previous section. Doing so make it a lot easier following how the code works. Once the table is full of data you can add it as a parameter to a stored procedure.

publicstaticvoidMergeExample(DataTablet){DBConnectmyDB=newDBConnect();SqlCommandobjEx=newSqlCommand();objEx.CommandType=CommandType.StoreProcedure;ojbEx.CommandText="MergeExampleSP";objEx.Parameters.AddWithValue("@tableType",t);myDB.DoUpdateWithDSCmdOjb(objEx);myDB.CloseConnection();}

FOR THE LOVE OF GOD CLOSE ALL YOUR DATABASE CONNECTIONS!

###SQL Merge Function ####Notes: SQL Merge is a really powerful function. It can take data merge it into a table either by doing INSERT or doing an UPDATE.

Now this is the example of the what a stored procedure will look like. Look at the SQL code first before reading the explanation.

	ALTER PROCEDURE [dbo].[MergeExampleSP]
(
@tableType ExampleOfUserDefinedTable READONLY --The READONLY is required so the database knows it isn't doing anything except reading the table.
)
ASBEGIN
MERGE INTO dbo.FacultyAS m1 --m1 an alias for Faculty, this is the Target Table
USING @tblAccessRequests AS m2 --m2 is alias for the parameter, this is the Source TableONm1.id=m2.id--id is the primary key for Faculty
WHEN MATCHED THEN --If primary key matches between both tables UPDATE firesUPDATESETm1.first_name=m2.first_name,
m1.last_name=m2.last_name,
m1.creation_date= GETDATE(),
m1.last_modified= GETDATE()
WHEN NOT MATCHED BY TARGET THEN --If primary key does not match INSERT fires
INSERT (id, first_name, last_name, creation_date, last_modified)
VALUES (m2.id, m2.first_name, m2.last_name, GETDATE(), GETDATE()); --The ; ends the function
END

After MERGE INTO is the table within the database where the data is being merge into. The dbo. stands for DATABASE OWNER. It is required to make the MERGE function work. USING is telling the function what table is being used. The columns headers that were created in the User-Defined Table from the DataTable in C# are the same in SQL. The keyword ON is setting the primary key or unique constraint on which to use to identify a record within the table. If there is a match between that constraint between the target table and source table UPDATE will fire. This UPDATE takes the records from the source table and sets the target tables records to those values based on the constraint matched. The last two records set creation_date and last_modified are set by the systems current date. You could also set these values with whatever you want.

If the constraint between the target table and source table is not the same then the INSERT is fired. WHEN NOT MATCHED BY TARGET THEN means just that. If there is a record within the source table that is not within the target table it will now be inserted into the target table. Changing WHEN NOT MATCHED BY TARGET THEN is changed to WHEN NOT MATCHED BY SOURCE this will be changing something within the target table. If the code about was changed like that it would update all records that matched between the target table and the source table, insert any records present within the source table but not the target table, all records within the target table that are not present within the source table will be deleted. Syntax is important.

About

a repo of database functions

Resources

Stars

1 star

Watchers

6 watching

Forks

Releases

Packages

Contributors

Languages