Thursday, July 5, 2018

SQL - How to drop table with foreign key constraints

In SQL Server the foreign key constraints must be dropped before dropping the table.

Please use the below script to find and drop all foreign key constraints of the table.


--Find and drop the constraints

DECLARE @dynamicSQL VARCHAR(MAX)
DECLARE MY_CURSOR CURSOR

LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT dynamicSQL = 'ALTER TABLE [' +  OBJECT_SCHEMA_NAME(parent_object_id) + '].[' + OBJECT_NAME(parent_object_id) + '] DROP CONSTRAINT [' + name + ']'
FROM sys.foreign_keys
WHERE object_name(referenced_object_id)  in ('table1', 'table2', 'table3')
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @dynamicSQL
WHILE @@FETCH_STATUS = 0
BEGIN

PRINT @dynamicSQL
EXEC (@dynamicSQL)

FETCH NEXT FROM MY_CURSOR INTO @dynamicSQL
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR


-- Drop tables
DROP 'table1'
DROP 'table2'
DROP 'table3'


Thursday, April 5, 2018

What are the special characters in XML?

How to handle special characters in XML?

In XML, five characters are reserved for internal use and you must replace them by replacement text when they are used in data.

The following table shows the characters that must be replaced by their replacement text in XML files

XML Special Characters

Reserved Character Replacement Text
" "
' '
> >
< &lt;
& &amp;