Quantcast
Channel: Welcome To TechBrothersIT
Viewing all 1873 articles
Browse latest View live

C# - How to remove last character from string in C#

$
0
0

Scenario: Download Script

You are working as C# or dot net developer, you are writing a program in which you need to remove last character from string values.

There could be different scenarios
Let's say you have a folder path and you don't want the \ at the end
you have a string that always come with comma (,) at the end and you don't need comma at the end
You have the address that always come with address 1, address 2 or address 3. You need to remove last characters.


You can use TrimEnd Method to remove last character if you are aware of the character, as I did in below examples to remove "\" and comma ",". If you are not aware of the last character, you can use Substring method to remove last character from string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//string with \ at the end, need to remove
string Folderpath = @"C:\Source\";
//string with comma ( , ) at the end, need to remote
string Name = "
Welcome to TechBrothersIT.com,";

//Use the TrimEnd to remove last character from string
string Folderpathtrimed=Folderpath.TrimEnd('\\');
string NameTrimed = Name.TrimEnd(',');



//Let's say if we are not sure about the last character but always want to remove
string Address = "
This is test address 1";
string AddressTrimed = Address.Substring(0, Address.Length - 1);

//Print the values to check if last character is removed
Console.WriteLine("
FolderPath variable value:" + Folderpath);
Console.WriteLine("
FolderPathtrimed variable value:" + Folderpathtrimed);
Console.WriteLine("
Name variable value:" + Name);
Console.WriteLine("
NameTrimed variable value:" + NameTrimed);
Console.WriteLine("
Address variable value:" + Address);
Console.WriteLine("
AddressTrimed variable value:" + AddressTrimed);
Console.ReadLine();
}
}
}

Here are the output from Console Application before and after removing last characters from string.
How to trim last character from string in C#


C# - How to remove Extension from File Name in C#

$
0
0

Scenario : Download Script

You are working as C# or dot net developer, You need to read the file names from a folder and then remove the extension from file names.

The file extensions can be of different lengths, such as .txt is only three characters but .xlsx is 4 character extension. We can't simply remove last 3 or 4 characters from file name to get only file name.

As the extension are added after dot (.) , if we can find the position of dot and remove the string from there, we will be left with file name only. 

There could be special scenario when file name can have dot (.) as part of file name. That means that to find the extension's dot, we need to find the last dot in file name.

Here are some sample files I have in C:\Source folder.

How to remove extension from file name in C# 

I wrote below C# Console Application, this will read the file names from a folder. We will use Substring Method with LastIndexOf Method to remove extension from each file name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//add namespace
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//Source Folder path for files
string Folderpath = @"C:\Source\";

//Reading file names one by one
string[] fileEntries = Directory.GetFiles(Folderpath, "
*.*");
foreach (string FileName in fileEntries)
{

//declare a variable and get file name only in it from FileName variable
string FileNameOnly = FileName.Substring(0, FileName.LastIndexOf("
."));

//Print the values for FileName and FileNameOnly variables
Console.WriteLine("
FileName variable Value :" + FileName);
Console.WriteLine("
FileNameOnly variable Value :" + FileNameOnly);
Console.ReadLine();

}
}
}
}

Here are the output after and before removing the extension from file name in C#. 
How to remove extension from files in C#



C# - How to remove last X Characters from a string in C#

$
0
0

Scenario: Download Script

You are working as C# or dot net developer. You are writing a program in which you need to remove last x characters from a string.

To make it more real time problem, think about a scenario where you read text or csv files from a folder and then you need to remove the extension that is 4 characters (.csv or .txt).

The below code can be used to remove x characters from a string. Replace 4 with your number or characters you would like to remove.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//add namespace
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//declare FileName variable and save mytextfile.txt value
string FileName = "mytextfile.txt";

//create variable FileNameRemoved and save values after removing last 4 characters from FileName variable
string FileNameRemoved = FileName.Substring(0, FileName.Length - 4);

//Print the variable values
Console.WriteLine(
"FileName Variable Value: " + FileName);
Console.WriteLine(
"FileNameRemoved Variable Value: " + FileNameRemoved);


//If we want to remove the last x characters and save in the same variable
FileName = FileName.Remove(FileName.Length - 4, 1);
Console.WriteLine(
"FileName Variable Value by using Remove and save to save variable: " + FileName);
Console.ReadLine();

}
}
}

Here is output after removing 4 characters from a string value in C#.
How to remove last x characters from string in C#

C# - How to remove Character from String in C#

$
0
0

Scenario: Download Script

You are working as C# or dot net developer. You are writing a program in which you need to remove a character from string. 

Let's take real time example, you are reading file names which comes underscore "_". You want to remove all the underscores from file name.


In this example we used Replace Method. We find the character "_" and then replace with ""( no space).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//Declare File Name variable and save value
string FileName = "my_text_file_20160202.txt";

//create variable FileNameRemoved and save value of FileName variable after removing _
string FileNameRemoved = FileName.Replace("_", "");

//Print the variable values
Console.WriteLine(
"FileName Variable Value: " + FileName);
Console.WriteLine(
"FileNameRemoved Variable Value: " + FileNameRemoved);


//If you want to remove _ and save to same variable
FileName = FileName.Replace("_", "");
Console.WriteLine(
"FileName Variable Value after removing _:" + FileName);
Console.ReadLine();

}
}
}
How to remove character from string in C#

How to Create Table with Foreign Key Constraint in SQL Server - SQL Server / TSQL Tutorial Part 50

$
0
0

What is Foreign Key in SQL Server Table:

Foreign Key in a table is a column or group of columns that provides a link between data in two tables. The Foreign Key in a table points to the primary key in another table.

Let's create dbo.Customer Table with Primary Key by using below DDL statement

USE YourDatabaseName
GO

CREATETABLE dbo.Customer (
Customerid INTPRIMARYKEY
,FName VARCHAR(100)
,LName VARCHAR(100)
,SSN VARCHAR(10)
)
As you can see that Customerid is the primary key in dbo.Customer Table.

As we are ready with our first table and have the Primary Key, we are good to go and create second table with foreign Key Constraint.

CREATETABLE dbo.Orders (
OrderId INTIdentity(1, 1)
,OrderitemName VARCHAR(50)
,OrderItemAmt INT
,Customer_id INTFOREIGNKEYREFERENCES Customer(CustomerId)
)

You can see that we have added Customer_id column in dbo.Orders table that references to Customerid in dbo.Customer Table.

The primary key in first table is Customerid and Foreign Key Column in second table is Customer_id, that means the columns don't have to have same names. It is good idea to keep the same name so when you write queries and join the tables, you don't have to take a look which is primary key and which is foreign key, instead you would know that the same column names are in relationship.

Let's insert couple of records and see how Foreign Key Constraint works.

insertinto dbo.Customer 
(CustomerId,FName, LName,SSN)
values
(1,'Aamir','Shahzad','000-000-00')

insertinto dbo.Orders
(OrderItemName,OrderItemAmt,Customer_Id)
values ('TV',1,1)
Both records will be inserted just fine, as we are inserting same customerid in dbo.Orders that does exists in dbo.Customer.

If we will try to insert any value in dbo.Orders that is not present in dbo.Customer(CustomerId), It will through an error due to foreign key constraint.

insertinto dbo.Orders
(OrderItemName,OrderItemAmt,Customer_Id)
values ('TV',1,2)

When we run above query, it through error as we don't have 2 as Customerid in dbo.Customer table.

Msg 547, Level 16, State 0, Line 28
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Orders__Customer__286302EC". 
The conflict occurred in database "YourDatabaseName", table "dbo.Customer", column 'Customerid'.
The statement has been terminated.



How to create Foreign Key Constraint on Multiple Columns in SQL Server - SQL Server / TSQL Tutorial Part 67

$
0
0

Scenario: 

You are working as SQL Server developer, you need to create a table dbo.Customer with composite primary key by using columns FName and SSN. One you are done with creating primary key in dbo.Customer table, you need to create second table dbo.Orders and create foreign key constraint by using Primary Key columns.

Solution:

Let's create the dbo.Customer table with composite primary key by using below script.


USE YourDatabaseName
GO

CREATETABLE dbo.Customer (
Customerid
INTIdentity(1,1)
,FName
VARCHAR(100) NotNull
,LName
VARCHAR(100)
,SSN
VARCHAR(10) NotNull,
Constraint Pk_FName_SSN PrimaryKey (FName,SSN)
)


Notice that we have use Constraint Constraint_Name Primary Key(Column1, Column2) as highlighted in green to create Composite Primary Key.

Let's create the dbo.Orders table by using below script.


CREATETABLE dbo.Orders (
OrderId
INTIdentity(1, 1)
,OrderitemName
VARCHAR(50)
,OrderItemAmt
INT
,FirstName
VARCHAR(100),
SSN
VARCHAR(10) NotNull,
Constraint Fk_Order_Customer_FName_SSN
FOREIGNKEY (FirstName,SSN) REFERENCES dbo.Customer(FName,SSN)

)


To create Foreign Key Constraint with multiple columns you will be using script as highlighted in green. 
You will say 
Constraint Constraint_Name Foreign Key(Column1,Column2) References dbo.PrimaryKeyTable(PrimaryKeyColumn1,PrimaryKeyColumn2)

You can see that In dbo.Orders, I have columns FirstName instead of FName that I have in dbo.Customer table. It means that you don't have to have the same column name in both tables when you are creating foreign key reference.


Let's insert a records in each of table and see if all working fine with Foreign Key Constraint.
INSERTINTO dbo.Customer 
(FName, LName,SSN)
values
('Aamir','Shahzad','000-000-01')

INSERTINTO dbo.Orders
(OrderItemName,OrderItemAmt,FirstName,SSN)
values ('TV',1,'Aamir','000-000-01')
Records are inserted successfully. Let's verify by using Select query
How to create Foreign Key Constrain on Multiple Columns in SQL Server Table


Let's try to insert a value in dbo.Orders which does not exists in dbo.Customer. It should through us as error due to Foreign Key constraint.

INSERTINTO dbo.Orders
(OrderItemName,OrderItemAmt,FirstName,SSN)
values ('TV',1,'Aamir','000-000-02')

As highlighted SSN value does not exists in dbo.Customer, we got below error.

Msg 547, Level 16, State 0, Line 30
The INSERT statement conflicted with the FOREIGN KEY constraint "Fk_Order_Customer_FName_SSN". The conflict occurred in database "YourDatabaseName", table "dbo.Customer".
The statement has been terminated. 



*** The order of columns should be same what you have in primary key when we create foreign key constraint. If I try to create foreign key constraint with different order, I will get below error.

CREATETABLE dbo.Orders (
OrderId INTIdentity(1, 1)
,OrderitemName VARCHAR(50)
,OrderItemAmt INT
,FirstName VARCHAR(100),
SSN VARCHAR(10) NotNull,
Constraint Fk_Order_Customer_FName_SSN
FOREIGNKEY
(SSN,FirstName)REFERENCES dbo.Customer(SSN,FName)
)

Msg 1776, Level 16, State 0, Line 13
There are no primary or candidate keys in the referenced table 'dbo.Customer' that match the referencing column list in the foreign key 'Fk_Order_Customer_FName_SSN'.
Msg 1750, Level 16, State 0, Line 13
Could not create constraint or index. See previous errors.








How to add Foreign key Constraint to existing table in SQL Server - SQL Server / TSQL Tutorial Part 68

$
0
0

Scenario:

You have already created two tables dbo.Customer and dbo.Orders. Primary Key is created on CustomerId column in dbo.Customer table.

USE YourDatabaseName
GO

CREATETABLE dbo.Customer (
Customerid INTPRIMARYKEY
,FName
VARCHAR(100)
,LName
VARCHAR(100)
,SSN
VARCHAR(10)
)

CREATETABLE dbo.Orders (
OrderId INTIdentity(1, 1)
,OrderitemName VARCHAR(50)
,OrderItemAmt INT
)

You need to alter dbo.Orders table and add Foreign key constraint for CustomerId from dbo.Customer.

Solution:

As the tables are already present, the below script can be used to alter dbo.Orders table and add Foreign Key constraint.

If the column already exists in second table on which you would like to create Foreign Key Constraint, you are good to run the below script. As we don't have the column in table, we are going to add CustomerId column in dbo.Orders table first. The column Name does not has to match with first table column in our case dbo.Customer.CustomerId

--Add new column to Table in case you don't have    
Altertable dbo.Orders
Add CustomerId int

--Add Foreign Key Constraint on Existing Table
Altertable dbo.Orders
AddConstraint Fk_CustomerId
ForeignKey(CustomerId) References dbo.Customer(CustomerId)

Create Foreign Key Constraint on Composite Columns
The below script can be used to create Foreign Key Constraint for Composite Columns.

USE YourDatabaseName
GO

CREATETABLE dbo.Customer (
Customerid INTIdentity(1,1)
,FName VARCHAR(100) NotNull
,LName VARCHAR(100)
,SSN VARCHAR(10) NotNull,
Constraint Pk_FName_SSN PrimaryKey (FName,SSN)
)


CREATETABLE dbo.Orders (
OrderId
INTIdentity(1, 1)
,OrderitemName
VARCHAR(50)
,OrderItemAmt
INT
,FirstName VARCHAR(100),
SSN VARCHAR(10) NotNull

)
Columns already exists in both tables so we don't have to add columns to second table. We only need to create Foreign Key Constrain. Below script can be used to create Foreign Key Constraint for composite columns.

     Altertable dbo.Orders
AddConstraint Fk_Order_Customer_FName_SSN
FOREIGNKEY (FirstName,SSN) REFERENCES dbo.Customer(FName,SSN)

You will write you syntax for your table 

Alter table dbo.YourTableName
Add Constraint Constraint_Name
Foreign Key (Column1FromYourTableName,Column2FromYourTable) References dbo.YourFirstTable(Column1FromPrimaryKey,Column2FromPrimaryKey) 





The ALTER TABLE statement conflicted with the FOREIGN KEY constraint in SQL Server - SQL Sever / TSQL Tutorial Part 69

$
0
0

Scenario:

You have created two tables dbo.Customer and dbo.Orders without having primary-foreign key relationship. After creating tables you inserted few records. Later you realized that you were supposed to add Foreign Key Constraint. When you tried to alter dbo.Orders table , you received error.

Create dbo.Customer and Dbo.Order Tables by using below script

USE YourDatabaseName
GO

CREATETABLE dbo.Customer (
Customerid INTPRIMARYKEY
,FName VARCHAR(100)
,LName VARCHAR(100)
,SSN VARCHAR(10)
)

CREATETABLE dbo.Orders (
OrderId INTIdentity(1, 1)
,OrderitemName VARCHAR(50)
,OrderItemAmt INT,
CustomerId int
)
Insert sample records by using below script.

INSERTINTO dbo.Customer 
(CustomerId,FName, LName,SSN)
VALUES
(
1,'Aamir','Shahzad','000-000-00')

INSERTINTO dbo.Orders
(OrderItemName,OrderItemAmt,Customerid)
values ('TV',2,2)
Now let's add Foreign Key Constraint

Altertable dbo.Orders
AddConstraint Fk_CustomerId
ForeignKey(CustomerId) References dbo.Customer(CustomerId)
When we execute above script, we get below error.

Msg 547, Level 16, State 0, Line 31
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "Fk_CustomerId". The conflict occurred in database "YourDatabaseName", table "dbo.Customer", column 'Customerid'.

As dbo.Customer has value 1 for CustomerId column and in dbo.Orders table column CustomerId has value 2. The values does not match with each other. That is the reason we received above error.

Solutions:

1) Fix the data in second table (dbo.Orders)
We can fix the data in second table and update the CustomerId column values. Once we will have correct data that matches with our Primary Table ( Dbo.Customer.CustomerId), it will let us create Foreign Key Constraint without any issue.

2) Use Alter Table with Nocheck ( Ignore existing data)
If you don't care about relationship of existing data. You can use With NoCheck with alter table statement and it will ignore the check to validate data and create Foreign Key Constraint. Once the Foreign Key Constraint will be created, it will enforce integrity for any new records inserted.

Altertable dbo.Orders withNocheck
AddConstraint Fk_CustomerId
ForeignKey(CustomerId) References dbo.Customer(CustomerId)


Cannot truncate table because it is being referenced by a FOREIGN KEY constraint - SQL Server / TSQL Tutorial Part 70

$
0
0

Scenario: 

You need to truncate a table but when you try to execute truncate table tableName. You get below error.

Msg 4712, Level 16, State 1, Line 43
Cannot truncate table 'SchemaName.TableName' because it is being referenced by a FOREIGN KEY constraint.

How would you truncate this table?

Solution:

As the table in involved in Foreign Key relationship, you need to drop the foreign key constraint first and then execute the truncate table statement.

Let's demo this example, I am going to create two table dbo.Customer and dbo.Orders and then create Foreign Key Constraint on one of the column of Dbo.Orders to dbo.Customer table.

USE YourDatabaseName
GO

CREATETABLE dbo.Customer (
Customerid INTPRIMARYKEY
,FName VARCHAR(100)
,LName VARCHAR(100)
,SSN VARCHAR(10)
)

CREATETABLE dbo.Orders (
OrderId INTIdentity(1, 1)
,OrderitemName VARCHAR(50)
,OrderItemAmt INT,
CustomerId int
)

--Create Foreign Key Constraint
Altertable dbo.Orders withNocheck
AddConstraint Fk_CustomerId
ForeignKey(CustomerId) References dbo.Customer(CustomerId)
Now if I try to truncate dbo.Orders table, it will throw no error. But when I try to truncate dbo.Customer table it will throw error as dbo.Customer is begin references by Foreign Key Constraint.

How to truncate a table which is reference by Foreign Key Constraint in SQL Server

We can drop the constraint for now, truncate the table and then recreate Foreign key constraint.

To find the Foreign Key Constraints on a table, you can use below statement.

SELECT * 
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('dbo.Customer')
How to get Constraint name from system tables in SQL Server
The below script can be used to generate drop Constraint statement for your table

SELECT
'ALTER TABLE '
+ OBJECT_SCHEMA_NAME(parent_object_id)
+'.[' + OBJECT_NAME(parent_object_id)
+'] DROP CONSTRAINT '
+ name as DropFKConstraint
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('dbo.Customer'
How to drop Foreign Key Constraint on Table in SQL Server
Take the result for Drop Foreign Key Constraint and execute, After that run your truncate table statement to truncate table. It should complete without any error.

How to get Parent Table, Reference Table, Foreign Key Constraint Name and Columns in SQL Server - SQL Server / TSQL Tutorial Part 71

$
0
0

Scenario:

You are working as SQL Server Developer, you are asked to provide the query that should return all the parent tables, reference tables, Foreign Key Constraints and Columns used in Foreign Key Constraint definition.

Solution:

We can use the system views to gather this information. In our below query we will be using three

system views
sys.foreign_keys
sys.foreign_key_columns
sys.columns 

to answer the request. As we can have composite primary key columns used in Foreign Key Constraint, I have used FOR XML Path to concatenate rows into column so can provide list of columns in single row.

;With CTE_FK AS (
SELECT Schema_Name(Schema_id) as TableSchemaName,
object_name(FK.parent_object_id) ParentTableName,
object_name(FK.referenced_object_id) ReferenceTableName,
FK.name AS ForeignKeyConstraintName,c.name as ReferencedColumnList,
cf.name as ParentColumnName
FROM sys.foreign_keys AS FK
INNERJOIN sys.foreign_key_columns AS FKC
ON FK.OBJECT_ID = FKC.constraint_object_id
INNERJOIN sys.columns c
on c.OBJECT_ID = FKC.referenced_object_id
AND c.column_id = FKC.referenced_column_id
INNERJOIN sys.columns cf
on cf.OBJECT_ID = FKC.parent_object_id
AND cf.column_id = FKC.parent_column_id
)
Select TableSchemaName,
ParentTableName,
ReferenceTableName,
ForeignKeyConstraintName,stuff((
Select','+ParentColumnName
from CTE_FK i
where i.ForeignKeyConstraintName=o.ForeignKeyConstraintName
and i.TableSchemaName=o.TableSchemaName
and i.ParentTableName=o.ParentTableName
and i.ReferenceTableName=o.ReferenceTableName
for xml path('')), 1, 1, '') ParentColumnList
,stuff((
Select','+ReferencedColumnList
from CTE_FK i
where i.ForeignKeyConstraintName=o.ForeignKeyConstraintName
and i.TableSchemaName=o.TableSchemaName
and i.ParentTableName=o.ParentTableName
and i.ReferenceTableName=o.ReferenceTableName
for xml path('')), 1, 1, '') RefColumnList
from CTE_FK o
groupby
tableSchemaName,
ParentTableName,
ReferenceTableName,
ForeignKeyConstraintName


I executed above script on one of my database and here is output with Schema Name,Parent Table Name, Referenced Table Name, Foreign Key Constraint Name, Parent Column List and Reference Column List used in Constraint.
How to get Parent Table, Referenced Table,Foreign Key Constraint Name, Columns list in SQL Server

How to drop Foreign Key Constraints in SQL Server Database for all the tables - SQL Server / TSQL Tutorial Part 72

$
0
0

Scenario:

You are working as SQL Server developer, you are asked to provide the scripts those can be used to drop Foreign Key Constraints on all the tables in a database if exists.

Solution:

We can use system view to generate the drop Foreign Key Constraints for all the tables in SQL Server Database by using below query.

USE YourdatabaseName
go
-- Drop Foreign Key Constraints Script
SELECTdistinct'ALTER TABLE '
+ '['+ Schema_name(FK.schema_id)
+ '].['+ OBJECT_NAME(FK.parent_object_id)
+ ']'+ ' DROP CONSTRAINT '
+ '[' + FK.name + ']'AS DropConstraintQuery
FROM sys.foreign_keys AS FK
How to drop all the Foreign Key Constraints in SQL Server Database
Execute above query and then take the results and run in SSMS to drop all the Foreign Key Constraint in database.

How to generate scripts to Re-Generate Foreign Key Constraints in SQL Server Database - SQL Server / TSQL Tutorial Part 73

$
0
0

Scenario:

You need to truncate all the tables in SQL Server database, when when you run truncate statement, you get error below error.
Msg 4712, Level 16, State 1, Line 43
Cannot truncate table 'SchemaName.TableName' because it is being referenced by a FOREIGN KEY constraint.

The easy way would be drop the Foreign Key Constraints, truncate the tables and recreate the Foreign Key Constraint again.

I wrote a post that you can use to generate Drop Foreign Key Constraints in a database. Click here. 
But before we drop them, we need to generate the create Foreign key Constraints scripts so we can run after truncating the table.

You can use below script to generate truncate table statement for all the user tables from a database.

Select'Truncate table '+'['
+Schema_name(Schema_id)
+'].['+name+']'as TruncateTablesScript
from sys.tables
where is_ms_shipped=0

The below script can be used to re-generate Foreign Key Constraint in a database.

;With CTE_FK AS (
SELECT Schema_Name(Schema_id) as TableSchemaName,
object_name(FK.parent_object_id) ParentTableName,
object_name(FK.referenced_object_id) ReferenceTableName,
FK.name AS ForeignKeyConstraintName,c.name as RefColumnName,
cf.name as ParentColumnList
FROM sys.foreign_keys AS FK
INNERJOIN sys.foreign_key_columns AS FKC
ON FK.OBJECT_ID = FKC.constraint_object_id
INNERJOIN sys.columns c
on c.OBJECT_ID = FKC.referenced_object_id
AND c.column_id = FKC.referenced_column_id
INNERJOIN sys.columns cf
on cf.OBJECT_ID = FKC.parent_object_id
AND cf.column_id = FKC.parent_column_id
where fk.is_ms_shipped=0
)
Select
'Alter table ['+TableSchemaName+'].['+ParentTableName+']'
+' Add Constraint '+ForeignKeyConstraintName+
' Foreign Key('+stuff((
Select','+ParentColumnList
from CTE_FK i
where i.ForeignKeyConstraintName=o.ForeignKeyConstraintName
and i.TableSchemaName=o.TableSchemaName
and i.ParentTableName=o.ParentTableName
and i.ReferenceTableName=o.ReferenceTableName
for xml path('')), 1, 1, '')+') References '+
'['+TableSchemaName+'].['+ReferenceTableName+']('+stuff((
Select','+RefColumnName
from CTE_FK i
where i.ForeignKeyConstraintName=o.ForeignKeyConstraintName
and i.TableSchemaName=o.TableSchemaName
and i.ParentTableName=o.ParentTableName
and i.ReferenceTableName=o.ReferenceTableName
for xml path('')), 1, 1, '')+')'
AS CreateForeignKeyConstraintScript,
ParentTableName,
ReferenceTableName,
ForeignKeyConstraintName
from CTE_FK o
groupby
tableSchemaName,
ParentTableName,
ReferenceTableName,
ForeignKeyConstraintName
How to generate script to re-create Foreign Key Constraint in SQL Server Database
Take the results from CreateForeignKeyConstraintScript Column. I suggest you to run the scripts in DEV or QA first to make sure all working fine before you run in Production.

Could not drop object because it is referenced by a FOREIGN KEY constraint - SQL Server / TSQL Tutorial Part 74

$
0
0

Scenario:

You are working as SQL Server DBA or Developer, You need to drop a table from a database. When you execute drop table SchemaName.TableName statement, you get below error.

Msg 3726, Level 16, State 1, Line 12
Could not drop object 'SchemaName.TableName' because it is referenced by a FOREIGN KEY constraint.

Now we know that the table is referenced by Foreign Key Constraint. The problem is how to find which table has that Foreign Key Constraint that is referencing to this table.

Solution:

1) There are many ways to get this information. We can use system views to find the name of table which has the Foreign Key Constraint which is referencing our Primary Table.

SELECT Schema_Name(Schema_id) as TableSchemaName,
object_name(FK.parent_object_id) ParentTableName,
object_name(FK.referenced_object_id) ReferenceTableName
FROM sys.foreign_keys AS FK
WHERE object_name(FK.referenced_object_id)='YourTableName'
and Schema_Name(Schema_id)='YourTableSchemaName'


I executed above script for my customer table which is present in dbo schema and here is what I got.
How to find which table's Foreign Key is referencing to Table in SQL Server.


Now we know that Ord is the table which has the Foreign Key Constraint which is referencing our table. We can go ahead and drop the foreign key Constraint and then drop our table.

2) Use System Stored Procedure sp_fkeys

We can use system Stored Procedure to get the Foreign Key Constraints information which are referencing to our table. If my table name is Customer, I can run script as below

EXEC sp_fkeys 'Customer'

How to get Foreign Key Constraint name for a Table in SQL Server

The sp_fkeys returns very detailed information, few of the columns are not shown in snapshot above. here is the list of columns it will return.


  • PKTABLE_QUALIFIER
  • PKTABLE_OWNER
  • PKTABLE_NAME
  • PKCOLUMN_NAME
  • FKTABLE_QUALIFIER
  • FKTABLE_OWNER
  • FKTABLE_NAME
  • FKCOLUMN_NAME
  • KEY_SEQ
  • UPDATE_RULE
  • DELETE_RULE
  • FK_NAME
  • PK_NAME



How to Drop Foreign Key Constraint in SQL Server Database - SQL Server / TSQL Tutorial Part 75

$
0
0

Scenario:

You are working as SQL Server developer and you need to prepare the script to drop the Foreign Key Constraint which was created on dbo.Orders table.

Solution:

Let's create dbo.Customer and dbo.Orders sample tables and include Foreign Key Constraint as part of create table by using below script.

USE YourDatabaseName
GO

CREATETABLE dbo.Customer (
Customerid INTPRIMARYKEY
,FName
VARCHAR(100)
,LName
VARCHAR(100)
,SSN
VARCHAR(10)
)


CREATETABLE dbo.Orders (
OrderId
INTIdentity(1, 1)
,OrderitemName
VARCHAR(50)
,OrderItemAmt
INT
,Customer_id INTFOREIGNKEYREFERENCES Customer(CustomerId)
)

Once the tables are created and Foreign Key Constraint as well, you can use below statement to find the Foreign Key Constraint Name with table name.

USE YourDatabaseName
GO
Select
Schema_name(Schema_id) as SchemaName,
object_name(Parent_object_id) as TableName,
name as ForeignKeyConstraintName
from sys.foreign_keys
Find Foreign Key Constraint Name in SQL Server with Table Name

Now we know the constraint name, we can go ahead and write our drop constraint statement.

Syntax for Drop Foreign Key Constraint on Table
Alter Table SchemaName.TableName
Drop Constraint Constraint_Name

I used below statement to drop FK__Orders__Customer__164452B1 Foreign Key Constraint.

Altertable dbo.Orders
DropConstraint FK__Orders__Customer__164452B1

If you are interested to generate scripts to drop all Foreign Key Constraints in a database, Check this link.



The UPDATE statement conflicted with the REFERENCE constraint - SQL Server / TSQL Tutorial Part 76

$
0
0
Scenario:
You are working as SQL Server developer, You wrote an update statement for one of the table and getting below error.


Msg 547, Level 16, State 0, Line 32
The UPDATE statement conflicted with the REFERENCE constraint "FK_". 
The conflict occurred in database "YourDatabaseName", table "SchemaName.YourTableName", column 'ColumnName'.
The statement has been terminated.

How to resolve this issue?

Solution:

Let's create this error first by using below script. We are going to create two tables dbo.Customer and dbo.Orders. The tables has Primary-Foreign Key Relationship.


USE YourDatabaseName
GO

CREATETABLE dbo.Customer (
Customerid INTPRIMARYKEY
,FName VARCHAR(100)
,LName VARCHAR(100)
,SSN VARCHAR(10)
)


CREATETABLE dbo.Orders (
OrderId INTIdentity(1, 1)
,OrderitemName VARCHAR(50)
,OrderItemAmt INT
,Customer_id INTFOREIGNKEYREFERENCES Customer(CustomerId)
)


--insert sample data
insertinto dbo.Customer
(CustomerId,FName, LName,SSN)
values
(1,'Aamir','Shahzad','000-000-00')

insertinto dbo.Orders
(OrderItemName,OrderItemAmt,Customer_Id)
values ('TV',1,1)
How to update record when Column is referenced by Foreign Key Constraint in SQL Server

Now let's say if you feel that CustomerId value is incorrect in dbo.Customer and need to be updated. You wrote below update statement to update CustomerId to 100.

update dbo.Customer
set Customerid=100

You will get below error.

Msg 547, Level 16, State 0, Line 33
The UPDATE statement conflicted with the REFERENCE constraint "FK__Orders__Customer__1ED998B2". 
The conflict occurred in database "YourDatabaseName", table "dbo.Orders", column 'Customer_id'.
The statement has been terminated.

As there is no Customer_id value=100 in dbo.Orders table, You can't update the record in reference table. Now you thought that let's fix the Parent table first ( dbo.Orders) and then I can update the dbo.Customer table.

update dbo.Orders
set Customer_Id=100
Again you got the error as shown below, because we don't have CustomerId=100 available in dbo.Customer table.

Msg 547, Level 16, State 0, Line 36
The UPDATE statement conflicted with the FOREIGN KEY constraint "FK__Orders__Customer__1ED998B2".
 The conflict occurred in database "YourDatabaseName", table "dbo.Customer", column 'Customerid'.
The statement has been terminated.


From here we can come with with multiple solutions
1) Instead of updating the record, Insert the record in Reference Table ( Dbo.Customer), Then update the record in Parent table (Dbo.Orders) and finally delete the existing records from Reference Table.

--Insert Record in Reference Table First
insertinto dbo.Customer
(CustomerId,FName, LName,SSN)
values
(100,'Aamir','Shahzad','000-000-00')

--Update the Records in Parent Table
update dbo.Orders
set Customer_Id=100

--Delete the old record from Reference Table
Deletefrom dbo.Customer
where CustomerId=1
Check the records in table now.

How to update Column Value when referenced by Foreign Key Constraint in SQL Server 

2) Disable the Foreign Key Constraint and Update the Values Manually
Another solution can be, disable the Foreign Key constraint, update the records and finally enable the Foreign key again.

--Find the Foreign Key Constraint with Table Name
USE YourDatabaseName
GO
Select
Schema_name(Schema_id) as SchemaName,
object_name(Parent_object_id) as TableName,
name as ForeignKeyConstraintName
from sys.foreign_keys

Disable the Foreign Key Constraint by using below statement

Syntax
ALTER TABLE SchemaName.ParentTableName
NOCHECK CONSTRAINT Constraint_Name

I used below statement to disable Foreign Key constraint on dbo.Orders table.

--Disable Foregin Key by using NOCHECK
ALTERTABLE dbo.Orders
NOCHECKCONSTRAINT FK__Orders__Customer__2A4B4B5E

--Run Update Statements
update dbo.Customer
set Customerid=100

update dbo.Orders
set Customer_Id=100

Enable Foreign Key Constraint Syntax
ALTER TABLE SchemaName.ParentTableName
CHECK CONSTRAINT Constraint_Name


I execute below script to Enable Foreign Key Constraint on dbo.Orders table.

--Enable Foreign Key Constraint by using CHECK
ALTERTABLE dbo.Orders
CHECKCONSTRAINT FK__Orders__Customer__2A4B4B5E


How to disable all Foreign Key Constraint in SQL Server Database - SQL Server / TSQL Tutorial Part 77

$
0
0

Scenario: 

You are working as SQL Server developer, You need to provide the scripts to disable all the Foreign Key Constraint in SQL Server database.  This might be scenario where you need to load one time data and you are ok if data violate referential integrity.

Solution:


Let's get the list of Foreign Key Constraints from a SQL Server Database before we generate the disable script.

--Get List of Foreign Key Constraints if Enabled or Disabled
USE YourDatabaseName
GO
Select
Schema_name(Schema_id) as SchemaName,
object_name(Parent_object_id) as TableName,
name as ForeignKeyConstraintName,
CaseWhen Is_disabled=1 Then'No'
ELSE'Yes'Endas IsEnabled
from sys.foreign_keys

How to Check if Foreign Key Constraint is Enabled or Disabled in SQL Server

Now let's generate script to Disable Foreign Key Constraint in SQL Server Database

USE YourdatabaseName
go
-- Drop Foreign Key Constraints Script
SELECTdistinct'ALTER TABLE '
+ '['+ Schema_name(FK.schema_id)
+ '].['+ OBJECT_NAME(FK.parent_object_id)
+ ']'+ ' NOCHECK CONSTRAINT '
+ '[' + FK.name + ']'AS DisableConstraintQuery
FROM sys.foreign_keys AS FK
where is_disabled=0

How to generate Script to Disable All Foreign Key Constraints in SQL Server Database



How to Generate Script To Enable All Foreign Key Constraints in SQL Server Database - SQL Server / TSQL Tutorial Part 78

$
0
0

Scenario: 

You are working as SQL Server developer, You need to prepare scripts to enable all the Foreign Key Constraint in a database which are disabled. This could happen, maybe somebody has disabled Foreign Key Constraints for a data load where they don't care about violation of referential integrity and forgot to enable them later.


Solution:

First of all let's get the list of Foreign Key Constraints with status by using below query

--Get List of Foreign Key Constraints if Enabled or Disabled
USE YourDatabaseName
GO
Select
Schema_name(Schema_id) as SchemaName,
object_name(Parent_object_id) as TableName,
name as ForeignKeyConstraintName,
CaseWhen Is_disabled=1 Then'No'
ELSE'Yes'Endas IsEnabled
from sys.foreign_keys

How to check if Foreign Key Constraint is Disabled or Enabled in SQL Server Database
Now let's generate scripts to enable the Foreign Key Constraints which are disabled in SQL Server Database by using below query.

USE YourdatabaseName
go
-- Enable Foreign Key Constraints Script
SELECTdistinct'ALTER TABLE '
+ '['+ Schema_name(FK.schema_id)
+ '].['+ OBJECT_NAME(FK.parent_object_id)
+ ']'+ ' CHECK CONSTRAINT '
+ '[' + FK.name + ']'AS EnableConstraintQuery
FROM sys.foreign_keys AS FK
where is_disabled=1


How to generate script to enable all Foreign Key Constraints in SQL Server Database 
Copy the results and run in SSMS to enable disabled Foreign Key Constraints in SQL Server Database.

How to create Foreign Key Constraint With ON UPDATE CASCADE in SQL Server - SQL Server / TSQL Tutorial Part 79

$
0
0

Scenario:

In previous posts, we learn that if we have Foreign key Constraint with default setting and we try to update the value in column in Reference Table which is used as Reference Column in Foreign Key Constraint, we get error. We discussed multiple ways to handle the situation, please check this link.

Foreign Key Constraint does provide the option to set the Cascading action, we can create Foreign Key Constraint with Cascading Update. 

If Update Cascading settings is used, when we update the value in Referenced Table , it will also update the value in parent table (Foreign Key Table) column.

Let's test this scenario. Create two tables dbo.Customer and dbo.Orders with Foreign Key Relationship by given script


USE YourDatabaseName
GO

CREATETABLE dbo.Customer (
Customerid INTPRIMARYKEY
,FName
VARCHAR(100)
,LName
VARCHAR(100)
,SSN
VARCHAR(10)
)


CREATETABLE dbo.Orders (
OrderId
INTIdentity(1, 1)
,OrderitemName
VARCHAR(50)
,OrderItemAmt
INT
,Customer_id INTFOREIGNKEYREFERENCES
Customer(CustomerId) ONUPDATECASCADE

)


--insert sample data
insertinto dbo.Customer
(CustomerId,FName, LName,SSN)
values
(1,
'Aamir','Shahzad','000-000-00')

insertinto dbo.Orders
(OrderItemName,OrderItemAmt,Customer_Id)
values ('TV',1,1)


Let's check the data in tables by using select query
How to create Foreign Key Constraint with Update Cascade in SQL Server


Let's run our update statement on CustomerId in dbo.Customer table and see if it also update the column value in dbo.Orders for Customer_id.

update dbo.Customer
set Customerid=100
Let's check the data again in our tables 
How to enable Update Cascading with Foreign Key Constraint in SQL Server 

As we can see that the value is also updated in dbo.Orders.Customer_id column.  

How to create Foreign Key Constraint with ON DELETE CASCADE in SQL Server - SQL Server / TSQL Tutorial Part 80

$
0
0

Scenario:

You are working as SQL Server developer, you need to create two tables with Primary -Foreign Key Relationship. You want to create Foreign Key Constraint with setting if record will be deleted from Referenced Table (Primary Key Column Table), it should be deleted from Parent Table ( Foreign Key Constraint Table) as well.

Solution:

SQL Server let us use the the setting with Foreign Key Constraint called On DELETE CASCADE. If this rule is implemented, whenever record is deleted from Referenced Table( Primary Key Column Table), it will also be deleted from Parent Table ( Foreign Key Constraint Table).

Let's test this scenario with below script.

USE YourDatabaseName
GO

CREATETABLE dbo.Customer (
Customerid INTPRIMARYKEY
,FName
VARCHAR(100)
,LName
VARCHAR(100)
,SSN
VARCHAR(10)
)


CREATETABLE dbo.Orders (
OrderId
INTIdentity(1, 1)
,OrderitemName
VARCHAR(50)
,OrderItemAmt
INT
,Customer_id INTFOREIGNKEYREFERENCES
Customer(CustomerId) ONDELETECASCADE

)

--insert sample data
insertinto dbo.Customer
(CustomerId,FName, LName,SSN)
values
(1,
'Aamir','Shahzad','000-000-00')

Check the data in tables by using select query.

How to enable ON Delete CASCADE rule with Foreign Key Constraint in SQL Server

Let's delete the row from Referenced Table( Primary Key Column Table) and see if it also deletes from Parent Table ( Foreign Key Constraint Table) 


--Delete the Record from Referenced Table(PK Column Table)
Deletefrom dbo.Customer
where CustomerId=1


Check the tables again to see if record is deleted from both tables due to ON Delete Cascade rule on Foreign Key Constraint.
How to use ON Delete Cascade to delete records from multiple Tables in SQL Server Table

As we can see that the records are deleted from both tables due to ON DELETE CASCADE rule of Foreign Key Constraint. 



How to Create Foreign Key Constraint with ON DELETE SET NULL Option in SQL Server - SQL Server / TSQL Tutorial Part 81

$
0
0

Scenario:

You are working as SQL Server developer, you need to create two tables with Primary -Foreign Key Relationship. You want to create Foreign Key Constraint with setting if record will be deleted from Referenced Table (Primary Key Column Table), it should not be deleted from Parent Table ( Foreign Key Constraint Table) instead the value should be updated to Null.

Solution:

We can use ON DELETE SET NULL with Foreign Key Constraint definition to implement above requirement. 

Let's perform by using below script.
USE YourDatabaseName
GO

CREATETABLE dbo.Customer (
Customerid INTPRIMARYKEY
,FName
VARCHAR(100)
,LName
VARCHAR(100)
,SSN
VARCHAR(10)
)


CREATETABLE dbo.Orders (
OrderId
INTIdentity(1, 1)
,OrderitemName
VARCHAR(50)
,OrderItemAmt
INT
,Customer_id INTFOREIGNKEYREFERENCES
Customer(CustomerId) ONDELETESETNULL

)

--insert sample data
insertinto dbo.Customer
(CustomerId,FName, LName,SSN)
values
(1,
'Aamir','Shahzad','000-000-00')

insertinto dbo.Orders
(OrderItemName,OrderItemAmt,Customer_Id)
values ('TV',1,1)


Check the data in tables by using Select query 
How to create Foreign Key Constraint with ON DELETE SET NULL in SQL Server 


Let's delete the row from Referenced Table( Primary Key Column Table) and check if records still exists in Parent Table ( Foreign Key Constraint Table) and column value is updated to Null.

--Delete the Record from Referenced Table(PK Column Table)
Deletefrom dbo.Customer
where CustomerId=1

How to use ON DELETE SET NULL option with Foreign Key Constraint in SQL Server

As we can see that the record is deleted from Referenced Table( Primary Key Column Table) but still present in Parent Table ( Foreign Key Constraint Table)  but value is updated to Null as expected.


Viewing all 1873 articles
Browse latest View live