How to remove SQL Azure Data Sync objects manually - sql

Having given up on SQL Azure Data Sync for synchronizing data between two SQL Azure databases, how can I remove all the DataSync related objects (tables, triggers etc)?
E.g:
DataSync.<table>_dss_tracking
DataSync.schema_info_dss
DataSync.scope_config_dss
DataSync.scope_info_dss
And all the other objects? Is there a script that can be run?

There is an article on msgooroo.com:
https://msgooroo.com/GoorooTHINK/Article/15141/Removing-SQL-Azure-Sync-objects-manually/5215
Essentially the script is as follows:
-- Triggers
DECLARE #TRIGGERS_SQL VARCHAR(MAX) = (
SELECT
'DROP TRIGGER [' + SCHEMA_NAME(so.uid) + '].[' + [so].[name] + '] '
FROM sysobjects AS [so]
INNER JOIN sysobjects AS so2 ON so.parent_obj = so2.Id
WHERE [so].[type] = 'TR'
AND [so].name LIKE '%_dss_%_trigger'
FOR XML PATH ('')
)
PRINT #TRIGGERS_SQL
IF LEN(#TRIGGERS_SQL) > 0
BEGIN
EXEC (#TRIGGERS_SQL)
END
-- Tables
DECLARE #TABLES_SQL VARCHAR(MAX) = (
SELECT
'DROP TABLE [' + table_schema + '].[' + table_name + '] '
FROM
information_schema.tables where table_schema = 'DataSync'
FOR XML PATH ('')
)
PRINT #TABLES_SQL
IF LEN(#TABLES_SQL) > 0
BEGIN
EXEC (#TABLES_SQL)
END
-- Stored Procedures
DECLARE #PROC_SQL VARCHAR(MAX) = (
SELECT 'DROP PROCEDURE [' + routine_schema + '].[' + routine_name + '] '
FROM INFORMATION_SCHEMA.ROUTINES where ROUTINE_SCHEMA = 'DataSync' and routine_type = 'PROCEDURE'
FOR XML PATH ('')
)
PRINT #PROC_SQL
IF LEN(#PROC_SQL) > 0
BEGIN
EXEC (#PROC_SQL)
END
-- Types
DECLARE #TYPE_SQL VARCHAR(MAX) = (
SELECT
'DROP TYPE [' + SCHEMA_NAME(so.uid) + '].[' + [so].[name] + '] '
FROM systypes AS [so]
where [so].name LIKE '%_dss_bulktype%'
AND SCHEMA_NAME(so.uid) = 'Datasync'
FOR XML PATH ('')
)
PRINT #TYPE_SQL
IF LEN(#TYPE_SQL) > 0
BEGIN
EXEC (#TYPE_SQL)
END
-- Schema
DROP SCHEMA DataSync

I recently ran into this issue and while the script in the accepted answer did remove the DataSync schema, it did not remove the dss or TaskHosting schemas nor the symmetric key objects that were preventing me from exporting my database.
I ended up needing to contact Azure support to get everything removed. Here is the script that they gave me:
declare #n char(1)
set #n = char(10)
declare #triggers nvarchar(max)
declare #procedures nvarchar(max)
declare #constraints nvarchar(max)
declare #views nvarchar(max)
declare #FKs nvarchar(max)
declare #tables nvarchar(max)
declare #udt nvarchar(max)
-- triggers
select #triggers = isnull( #triggers + #n, '' ) + 'drop trigger [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects
where type in ( 'TR') and name like '%_dss_%'
-- procedures
select #procedures = isnull( #procedures + #n, '' ) + 'drop procedure [' + schema_name(schema_id) + '].[' + name + ']'
from sys.procedures
where schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
-- check constraints
select #constraints = isnull( #constraints + #n, '' ) + 'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.check_constraints
where schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
-- views
select #views = isnull( #views + #n, '' ) + 'drop view [' + schema_name(schema_id) + '].[' + name + ']'
from sys.views
where schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
-- foreign keys
select #FKs = isnull( #FKs + #n, '' ) + 'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.foreign_keys
where schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
-- tables
select #tables = isnull( #tables + #n, '' ) + 'drop table [' + schema_name(schema_id) + '].[' + name + ']'
from sys.tables
where schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
-- user defined types
select #udt = isnull( #udt + #n, '' ) +
'drop type [' + schema_name(schema_id) + '].[' + name + ']'
from sys.types
where is_user_defined = 1
and schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
order by system_type_id desc
print #triggers
print #procedures
print #constraints
print #views
print #FKs
print #tables
print #udt
exec sp_executesql #triggers
exec sp_executesql #procedures
exec sp_executesql #constraints
exec sp_executesql #FKs
exec sp_executesql #views
exec sp_executesql #tables
exec sp_executesql #udt
GO
declare #n char(1)
set #n = char(10)
declare #functions nvarchar(max)
-- functions
select #functions = isnull( #functions + #n, '' ) + 'drop function [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects
where type in ( 'FN', 'IF', 'TF' )
and schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
print #functions
exec sp_executesql #functions
GO
--update
DROP SCHEMA IF EXISTS [dss]
GO
DROP SCHEMA IF EXISTS [TaskHosting]
GO
DROP SCHEMA IF EXISTS [DataSync]
GO
DROP USER IF EXISTS [##MS_SyncAccount##]
GO
DROP ROLE IF EXISTS [DataSync_admin]
GO
DROP ROLE IF EXISTS [DataSync_executor]
GO
DROP ROLE IF EXISTS [DataSync_reader]
GO
declare #n char(1)
set #n = char(10)
--symmetric_keys
declare #symmetric_keys nvarchar(max)
select #symmetric_keys = isnull( #symmetric_keys + #n, '' ) + 'drop symmetric key [' + name + ']'
from sys.symmetric_keys
where name like 'DataSyncEncryptionKey%'
print #symmetric_keys
exec sp_executesql #symmetric_keys
-- certificates
declare #certificates nvarchar(max)
select #certificates = isnull( #certificates + #n, '' ) + 'drop certificate [' + name + ']'
from sys.certificates
where name like 'DataSyncEncryptionCertificate%'
print #certificates
exec sp_executesql #certificates
GO
print 'Data Sync clean up finished'

After trying a few queries, this is the only one that worked:
declare #n char(1)
set #n = char(10)
declare #triggers nvarchar(max)
declare #procedures nvarchar(max)
declare #constraints nvarchar(max)
declare #FKs nvarchar(max)
declare #tables nvarchar(max)
declare #udt nvarchar(max)
-- triggers
select #triggers = isnull( #triggers + #n, '' ) + 'drop trigger [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects
where type in ( 'TR') and name like '%_dss_%'
-- procedures
select #procedures = isnull( #procedures + #n, '' ) + 'drop procedure [' + schema_name(schema_id) + '].[' + name + ']'
from sys.procedures
where schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
-- check constraints
select #constraints = isnull( #constraints + #n, '' ) + 'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.check_constraints
where schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
-- foreign keys
select #FKs = isnull( #FKs + #n, '' ) + 'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']'
from sys.foreign_keys
where schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
-- tables
select #tables = isnull( #tables + #n, '' ) + 'drop table [' + schema_name(schema_id) + '].[' + name + ']'
from sys.tables
where schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
-- user defined types
select #udt = isnull( #udt + #n, '' ) + 'drop type [' + schema_name(schema_id) + '].[' + name + ']'
from sys.types
where is_user_defined = 1
and schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
order by system_type_id desc
print #triggers
print #procedures
print #constraints
print #FKs
print #tables
print #udt
exec sp_executesql #triggers
exec sp_executesql #procedures
exec sp_executesql #constraints
exec sp_executesql #FKs
exec sp_executesql #tables
exec sp_executesql #udt
declare #functions nvarchar(max)
-- functions
select #functions = isnull( #functions + #n, '' ) + 'drop function [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects
where type in ( 'FN', 'IF', 'TF' )
and schema_name(schema_id) = 'dss' or schema_name(schema_id) = 'TaskHosting' or schema_name(schema_id) = 'DataSync'
print #functions
exec sp_executesql #functions
DROP SCHEMA IF EXISTS [dss]
DROP SCHEMA IF EXISTS [TaskHosting]
DROP SCHEMA IF EXISTS [DataSync]
DROP USER IF EXISTS [##MS_SyncAccount##]
DROP USER IF EXISTS [##MS_SyncResourceManager##]
DROP ROLE IF EXISTS [DataSync_admin]
DROP ROLE IF EXISTS [DataSync_executor]
DROP ROLE IF EXISTS [DataSync_reader]
--symmetric_keys
declare #symmetric_keys nvarchar(max)
select #symmetric_keys = isnull( #symmetric_keys + #n, '' ) + 'drop symmetric key [' + name + ']'
from sys.symmetric_keys
where name like 'DataSyncEncryptionKey%'
print #symmetric_keys
exec sp_executesql #symmetric_keys
-- certificates
declare #certificates nvarchar(max)
select #certificates = isnull( #certificates + #n, '' ) + 'drop certificate [' + name + ']'
from sys.certificates
where name like 'DataSyncEncryptionCertificate%'
print #certificates
exec sp_executesql #certificates
print 'Data Sync clean up finished'
Source: https://github.com/vitomaz-msft/DataSyncMetadataCleanup
Thanks vitomaz!

If your architecture between Azure and SQL Server is still in place - you can simply unregister from the SQL Data Sync Agent which will delete above objects for you.

Microsoft released this script a while ago. Handy if you need to remove a single table
declare #TableName nvarchar(max)
set #TableName = 'yourTableName'
--In case you wish to delete objects related to all the tables you can uncomment the following:
--set #TableName = ''
-- Generate the script to drop Data Sync tables
select 'drop table [DataSync].['+ st.name+ '];' from sys.tables as st join sys.schemas as ss on ss.schema_id = st.schema_id
where ss.name = 'DataSync' and st.name like '%' + #TableName + '_dss_%'
-- Generate the script to drop Data Sync stored procedures
select 'drop procedure [DataSync].['+ sp.name+ '];' from sys.procedures as sp join sys.schemas as ss on ss.schema_id = sp.schema_id
where ss.name = 'DataSync' and sp.name like '%' + #TableName + '_dss_%'
-- Generate the script to delete Data Sync triggers
select 'drop trigger [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects where type = 'TR' and name like '%' + #TableName + '_dss_%'
-- Generate the script to delete Data Sync-related udtt
select 'drop type [DataSync].['+ st.name+ '];' from sys.types as st join sys.schemas as ss on st.schema_id = ss.schema_id
where ss.name = 'DataSync' and st.name like '%' + #TableName + '_dss_%'

If you have sync setup on an on premise SQL Server, un-registering the database from the Azure Sync Agent interface will do the necessary cleanup.

Related

Searching for data in all existing tables of a database

I want to search for the date '2017-08-08 09:26' in all existing tables of a database and get the column name and table name of the table that contains that date. So I can find that date in table A in column a.
example: '2017-08-08 09:26' exists in column 'a' of table 'A'
Please give me some suggestions for a solution.
Right now I am using this query in which I can search for columns, but I want to search the data in the columns of the tables in my database.
SELECT
sys.columns.name AS ColumnName,
sys.tables.name AS TableName
FROM
sys.columns
JOIN
sys.tables
ON
sys.columns.object_id = sys.tables.object_id
WHERE
sys.columns.name LIKE '%service%'
You need some good old-fashion dynamic SQL for this:
DECLARE #Sql varchar(max);
SELECT #Sql = STUFF((SELECT 'UNION ALL ' + CHAR(10) +'SELECT '''+
sys.columns.name +''' AS ColumnName, '''+
sys.tables.name +''' AS TableName '+ CHAR(10) +
'FROM sys.tables.name ' + CHAR(10) +
'WHERE '+ QUOTENAME(sys.columns.name) +' = #DateTimeValue ' + CHAR(10)
FROM
sys.columns
JOIN
sys.tables
ON
sys.columns.object_id = sys.tables.object_id
-- type ids: datetime2, smalldatetime, datetime
WHERE sys.columns.system_type_id IN(42, 58, 61)
FOR XML PATH('')
), 1, 11, 'DECLARE #DateTimeValue datetime = ''2017-08-08T09:26:00'';' + CHAR(10))
-- When using dynamic SQL, PRINT is your best friend.
PRINT #Sql
/*
#Sql should contain something like this:
DECLARE #DateTimeValue datetime = '2017-08-08T09:26:00';
SELECT 'Col1' AS ColumnName, 'Table1' AS TableName
FROM sys.tables.name
WHERE [Col1] = #DateTimeValue
UNION ALL
SELECT 'Col2' AS ColumnName, 'Table12' AS TableName
FROM sys.tables.name
WHERE [Col2] = #DateTimeValue
...
*/
-- Unremark only after you've seen what's inside #Sql.
--EXEC(#Sql)
Use the below script for getting entire DB search
DECLARE
#SearchStr nvarchar(100) = 'Pass'
BEGIN
DECLARE #Results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE #TableName nvarchar(256), #ColumnName nvarchar(128), #SearchStr2 varchar(110)
SET #TableName = ''
SET #SearchStr2 = QUOTENAME('%' + #SearchStr + '%','''')
WHILE #TableName IS NOT NULL
BEGIN
SET #ColumnName = ''
SET #TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > #TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (#TableName IS NOT NULL) AND (#ColumnName IS NOT NULL)
BEGIN
SET #ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(#TableName, 2)
AND TABLE_NAME = PARSENAME(#TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > #ColumnName
)
IF #ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + #TableName + '.' + #ColumnName + ''', LEFT(' + #ColumnName + ', 3630)
FROM ' + #TableName + ' (NOLOCK) ' +
' WHERE ' + #ColumnName + ' LIKE ' + #SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END

loop throgh all the data to search particular string [duplicate]

This question already has answers here:
Find a value anywhere in a database
(18 answers)
Closed 5 years ago.
I want to loop throgh all the column of all the tables available in my database to check which column containts string "Kroki Homes".
I have approx. 56 tables in my database. So it is hard to check in all the columns of these 56 tables. is there any easy way to achieve this in sql server?
You can create one procedure and can pass the string for search. I found this some where this might help you.
CREATE PROC [dbo].[SearchDataFromAllTables] (#SearchStr NVARCHAR(100))
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE #Results
(
ColumnName NVARCHAR(370),
ColumnValue NVARCHAR(3630)
)
DECLARE #TableName NVARCHAR(256)
, #ColumnName NVARCHAR(128)
, #SearchStr2 NVARCHAR(110)
SET #TableName = ''
SET #SearchStr2 = QUOTENAME('%' + #SearchStr + '%', '''')
WHILE #TableName IS NOT NULL
BEGIN
SET #ColumnName = ''
SET #TableName = (
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > #TableName
AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
)
WHILE (#TableName IS NOT NULL)
AND (#ColumnName IS NOT NULL)
BEGIN
SET #ColumnName = (
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(#TableName, 2)
AND TABLE_NAME = PARSENAME(#TableName, 1)
AND DATA_TYPE IN (
'char'
,'varchar'
,'nchar'
,'nvarchar'
)
AND QUOTENAME(COLUMN_NAME) > #ColumnName
)
IF #ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC (
'SELECT ''' + #TableName + '.' + #ColumnName + ''', LEFT(' + #ColumnName + ', 3630)
FROM ' + #TableName + ' (NOLOCK) ' + ' WHERE ' + #ColumnName + ' LIKE ' + #SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END
You need to write a stored procedure to scan through all the tables.
The script below gives to the tables and columns. From this you should create a SQL in-flight and execute dynamically to SELECT from tables. Let us know if you need more details.
SELECT tb.name AS table_name,
c.name AS column_name,
c.column_id,
tp.name AS column_data_type,
c.max_length,
c.precision,
c.scale,
CASE c.is_nullable WHEN 1 THEN 'YES' ELSE 'NO' END AS is_nullable
FROM sys.tables tb,
sys.columns c,
sys.types tp
WHERE tb.object_id = c.object_id
AND SCHEMA_NAME(tb.schema_id) = 'dbo'
AND c.user_type_id = tp.user_type_id
ORDER BY table_name, column_id;

Get all tables having Value in SQL Server [duplicate]

This question already has answers here:
Find a value anywhere in a database
(18 answers)
Closed 8 years ago.
I need to find a value wherever present in database.
Consider I need to find value "Fish" from Database.
Output I need is
Table Name | Column Name
--------------------------
Table 1 | columnName
Table 12 | columnName
and so on..
try this,
Declare #SearchStr nvarchar(100) = 'YorValue' -- Here type your text
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE #TableName nvarchar(256), #ColumnName nvarchar(128), #SearchStr2 nvarchar(110)
SET #TableName = ''
SET #SearchStr2 = QUOTENAME('%' + #SearchStr + '%','''')
WHILE #TableName IS NOT NULL
BEGIN
SET #ColumnName = ''
SET #TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > #TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (#TableName IS NOT NULL) AND (#ColumnName IS NOT NULL)
BEGIN
SET #ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(#TableName, 2)
AND TABLE_NAME = PARSENAME(#TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > #ColumnName
)
IF #ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + #TableName + '.' + #ColumnName + ''', LEFT(' + #ColumnName + ', 3630)
FROM ' + #TableName + ' (NOLOCK) ' +
' WHERE ' + #ColumnName + ' LIKE ' + #SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
drop table #Results
This query may help you
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE 'your column name'
ORDER BY schema_name, table_name;

Move tables from one database to another with primary key

I want to move the tables from one database to another, using dynamic SQL queries. I have a stored procedure to move the tables, but it is not moving the primary keys with table
This is my code:
set #cSQL='Select Name from '+#cSDBName+'.sys.tables where Type=''U'''
Insert into #t1Table
exec (#cSQL)
while((select count(tName) from #t1Table)>0)
begin
select top 1 #cName=tName from #t1Table
set #cSQL='Select * into '+#cDBName+'.dbo.'+#cName+' from '+#cSDBName+'.dbo.'+#cName +' where 1=2'
exec(#cSQL)
delete from #t1Table where tName=#cName
end
Here #cSDBName is the name of the source database and #cSQL is the SQL statement.
But this process won't move the primary key
Can anyone help me with this?
See this...
Clones an existing table to another table (without data)
Optionally drops and re-creates target table
Copies:
* Structure
* Primary key
* Indexes (including ASC/DESC, included columns, filters)
* Constraints (and unique constraints)
DOES NOT copy:
* Triggers
* File groups
* Probably a lot of other things
Note: Assumes that you name (unique) constraints with the table name in it (in order to not duplicate constraint names)
*/
SET NOCOUNT ON;
BEGIN TRANSACTION
--drop the table
if EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = #DestinationSchema AND TABLE_NAME = #DestinationTable)
BEGIN
if #RecreateIfExists = 1
BEGIN
exec('DROP TABLE [' + #DestinationSchema + '].[' + #DestinationTable + ']')
END
ELSE
RETURN
END
--create the table
exec('SELECT TOP (0) * INTO [' + #DestinationSchema + '].[' + #DestinationTable + '] FROM [' + #SourceSchema + '].[' + #SourceTable + ']')
DECLARE #PKSchema nvarchar(255), #PKName nvarchar(255)
SELECT TOP 1 #PKSchema = CONSTRAINT_SCHEMA, #PKName = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA = #SourceSchema AND TABLE_NAME = #SourceTable AND CONSTRAINT_TYPE = 'PRIMARY KEY'
--create primary key
IF NOT #PKSchema IS NULL AND NOT #PKName IS NULL
BEGIN
DECLARE #PKColumns nvarchar(MAX)
SET #PKColumns = ''
SELECT #PKColumns = #PKColumns + '[' + COLUMN_NAME + '],'
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
where TABLE_NAME = #SourceTable and TABLE_SCHEMA = #SourceSchema AND CONSTRAINT_SCHEMA = #PKSchema AND CONSTRAINT_NAME= #PKName
ORDER BY ORDINAL_POSITION
SET #PKColumns = LEFT(#PKColumns, LEN(#PKColumns) - 1)
exec('ALTER TABLE [' + #DestinationSchema + '].[' + #DestinationTable + '] ADD CONSTRAINT [PK_' + #DestinationTable + '] PRIMARY KEY CLUSTERED (' + #PKColumns + ')');
END
--create other indexes
DECLARE #IndexId int, #IndexName nvarchar(255), #IsUnique bit, #IsUniqueConstraint bit, #FilterDefinition nvarchar(max)
DECLARE indexcursor CURSOR FOR
SELECT index_id, name, is_unique, is_unique_constraint, filter_definition FROM sys.indexes WHERE type = 2 and object_id = object_id('[' + #SourceSchema + '].[' + #SourceTable + ']')
OPEN indexcursor;
FETCH NEXT FROM indexcursor INTO #IndexId, #IndexName, #IsUnique, #IsUniqueConstraint, #FilterDefinition;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #Unique nvarchar(255)
SET #Unique = CASE WHEN #IsUnique = 1 THEN ' UNIQUE ' ELSE '' END
DECLARE #KeyColumns nvarchar(max), #IncludedColumns nvarchar(max)
SET #KeyColumns = ''
SET #IncludedColumns = ''
select #KeyColumns = #KeyColumns + '[' + c.name + '] ' + CASE WHEN is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END + ',' from sys.index_columns ic
inner join sys.columns c ON c.object_id = ic.object_id and c.column_id = ic.column_id
where index_id = #IndexId and ic.object_id = object_id('[' + #SourceSchema + '].[' + #SourceTable + ']') and key_ordinal > 0
order by index_column_id
select #IncludedColumns = #IncludedColumns + '[' + c.name + '],' from sys.index_columns ic
inner join sys.columns c ON c.object_id = ic.object_id and c.column_id = ic.column_id
where index_id = #IndexId and ic.object_id = object_id('[' + #SourceSchema + '].[' + #SourceTable + ']') and key_ordinal = 0
order by index_column_id
IF LEN(#KeyColumns) > 0
SET #KeyColumns = LEFT(#KeyColumns, LEN(#KeyColumns) - 1)
IF LEN(#IncludedColumns) > 0
BEGIN
SET #IncludedColumns = ' INCLUDE (' + LEFT(#IncludedColumns, LEN(#IncludedColumns) - 1) + ')'
END
IF #FilterDefinition IS NULL
SET #FilterDefinition = ''
ELSE
SET #FilterDefinition = 'WHERE ' + #FilterDefinition + ' '
if #IsUniqueConstraint = 0
exec('CREATE ' + #Unique + ' NONCLUSTERED INDEX [' + #IndexName + '] ON [' + #DestinationSchema + '].[' + #DestinationTable + '] (' + #KeyColumns + ')' + #IncludedColumns + #FilterDefinition)
ELSE
BEGIN
SET #IndexName = REPLACE(#IndexName, #SourceTable, #DestinationTable)
exec('ALTER TABLE [' + #DestinationSchema + '].[' + #DestinationTable + '] ADD CONSTRAINT [' + #IndexName + '] UNIQUE NONCLUSTERED (' + #KeyColumns + ')');
END
FETCH NEXT FROM indexcursor INTO #IndexId, #IndexName, #IsUnique, #IsUniqueConstraint, #FilterDefinition;
END;
CLOSE indexcursor;
DEALLOCATE indexcursor;
--create constraints
DECLARE #ConstraintName nvarchar(max), #CheckClause nvarchar(max)
DECLARE constraintcursor CURSOR FOR
SELECT REPLACE(c.CONSTRAINT_NAME, #SourceTable, #DestinationTable), CHECK_CLAUSE from INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE t
INNER JOIN INFORMATION_SCHEMA.CHECK_CONSTRAINTS c ON c.CONSTRAINT_SCHEMA = TABLE_SCHEMA AND c.CONSTRAINT_NAME = t.CONSTRAINT_NAME
WHERE TABLE_SCHEMA = #SourceSchema AND TABLE_NAME = #SourceTable
OPEN constraintcursor;
FETCH NEXT FROM constraintcursor INTO #ConstraintName, #CheckClause;
WHILE ##FETCH_STATUS = 0
BEGIN
exec('ALTER TABLE [' + #DestinationSchema + '].[' + #DestinationTable + '] WITH CHECK ADD CONSTRAINT [' + #ConstraintName + '] CHECK ' + #CheckClause)
exec('ALTER TABLE [' + #DestinationSchema + '].[' + #DestinationTable + '] CHECK CONSTRAINT [' + #ConstraintName + ']')
FETCH NEXT FROM constraintcursor INTO #ConstraintName, #CheckClause;
END;
CLOSE constraintcursor;
DEALLOCATE constraintcursor;
COMMIT TRANSACTION
END
Well, the query you've written only moves the data. You've not specified the primary keys anywhere.
You'll need to either create the tables via your script, or alter the table via your script to define the primary keys.

SQL Server 2008 delete all tables under special schema

Hello I would like to know is is possible to drop all tables in database what was created under custom schema for example DBO1...with one sql query or special script.
Thanks
This will generate all the DROP TABLE statements for you and PRINT the SQL statement out.
You can then validate it's what you expect before copying and executing. Just make sure you are 100% sure...maybe take a backup first :)
DECLARE #SqlStatement NVARCHAR(MAX)
SELECT #SqlStatement =
COALESCE(#SqlStatement, N'') + N'DROP TABLE [DBO1].' + QUOTENAME(TABLE_NAME) + N';' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DBO1' and TABLE_TYPE = 'BASE TABLE'
PRINT #SqlStatement
Somewhat old thread I know, but I was looking for something like this and found the original answer very helpful. That said, the script will also try to drop views that might exist in that schema and give you an error message because you end up trying to drop a view by issuing a DROP TABLE statement.
I ended up writing this because I needed to drop all tables, views, procedures and functions from a given schema. Maybe not the most elegant way to accomplish this, but it worked for me and I thought I'd share.
DECLARE #Sql VARCHAR(MAX)
, #Schema varchar(20)
SET #Schema = 'Integration' --put your schema name between these quotes
--tables
SELECT #Sql = COALESCE(#Sql,'') + 'DROP TABLE %SCHEMA%.' + QUOTENAME(TABLE_NAME) + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = #Schema
AND TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_NAME
--views
SELECT #Sql = COALESCE(#Sql,'') + 'DROP VIEW %SCHEMA%.' + QUOTENAME(TABLE_NAME) + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = #Schema
AND TABLE_TYPE = 'VIEW'
ORDER BY TABLE_NAME
--Procedures
SELECT #Sql = COALESCE(#Sql,'') + 'DROP PROCEDURE %SCHEMA%.' + QUOTENAME(ROUTINE_NAME) + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = #Schema
AND ROUTINE_TYPE = 'PROCEDURE'
ORDER BY ROUTINE_NAME
--Functions
SELECT #Sql = COALESCE(#Sql,'') + 'DROP FUNCTION %SCHEMA%.' + QUOTENAME(ROUTINE_NAME) + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = #Schema
AND ROUTINE_TYPE = 'FUNCTION'
ORDER BY ROUTINE_NAME
SELECT #Sql = COALESCE(REPLACE(#Sql,'%SCHEMA%',#Schema), '')
PRINT #Sql
I know this is an old thread but I think the easiest way to do this is by using the undocumented sp_MSforeachtable stored procedure:
EXEC sp_MSforeachtable
#command1 = 'DROP TABLE ?'
, #whereand = 'AND SCHEMA_NAME(schema_id) = ''your_schema_name'' '
A detailed report on this stored procedure can be found here, but in case the link goes dead here are the highlights:
sp_MSforeachtable is a stored procedure that is mostly used to apply a T-SQL command to every table, iteratively, that exists in the current database.
[...]
realized that the question mark (?) it is used as the replacement of the table and during the execution it will be replaced by the appropriate table name.
#command1, #command2, #command3
sp_MSforeachtable stored procedure requires at least one command to be executed (#command1) but it allows up to 3 commands to be executed. Note that it will start to execute first the #command1 and then #command2 and #command3 by the last and this for each table.
#precommand
Use this parameter to provide a command to be executed before the #command1. It is useful to set variable environments or perform any kind of initialization.
#postcommand
Use this parameter to provide a command to be executed after all the commands being executed successfully. It is useful for control and cleanup processes.
#replacechar
By default, a table is represented by the question mark (?) character. This parameter allows you to change this character.
#whereand
By default, sp_MSforeachtable is applied to all user tables in the database. Use this parameter to filter the tables that you want to work with. On the next section, I will explain how you can filter the tables.
Building on the other answers, here is a stored procedure spDropSchema that drops all objects in a schema and the schema itself.
Note that the procedure tries to drop sequence objects too, so it will only work on SQL Server 2012 and above.
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'spDropSchema')
BEGIN
DROP PROCEDURE spDropSchema
END
GO
CREATE PROCEDURE spDropSchema(#Schema nvarchar(200))
AS
DECLARE #Sql NVARCHAR(MAX) = '';
--constraints
SELECT #Sql = #Sql + 'ALTER TABLE '+ QUOTENAME(#Schema) + '.' + QUOTENAME(t.name) + ' DROP CONSTRAINT ' + QUOTENAME(f.name) + ';' + CHAR(13)
FROM sys.tables t
inner join sys.foreign_keys f on f.parent_object_id = t.object_id
inner join sys.schemas s on t.schema_id = s.schema_id
WHERE s.name = #Schema
ORDER BY t.name;
--tables
SELECT #Sql = #Sql + 'DROP TABLE '+ QUOTENAME(#Schema) +'.' + QUOTENAME(TABLE_NAME) + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = #Schema AND TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_NAME
--views
SELECT #Sql = #Sql + 'DROP VIEW '+ QUOTENAME(#Schema) +'.' + QUOTENAME(TABLE_NAME) + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = #Schema AND TABLE_TYPE = 'VIEW'
ORDER BY TABLE_NAME
--procedures
SELECT #Sql = #Sql + 'DROP PROCEDURE '+ QUOTENAME(#Schema) +'.' + QUOTENAME(ROUTINE_NAME) + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = #Schema AND ROUTINE_TYPE = 'PROCEDURE'
ORDER BY ROUTINE_NAME
--functions
SELECT #Sql = #Sql + 'DROP FUNCTION '+ QUOTENAME(#Schema) +'.' + QUOTENAME(ROUTINE_NAME) + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = #Schema AND ROUTINE_TYPE = 'FUNCTION'
ORDER BY ROUTINE_NAME
--sequences
SELECT #Sql = #Sql + 'DROP SEQUENCE '+ QUOTENAME(#Schema) +'.' + QUOTENAME(SEQUENCE_NAME) + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.SEQUENCES
WHERE SEQUENCE_SCHEMA = #Schema
ORDER BY SEQUENCE_NAME
--types
SELECT #Sql = #Sql + 'DROP TYPE ' + QUOTENAME(#Schema) + '.' + QUOTENAME(t.name) + ';' + CHAR(13)
FROM sys.types t
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE t.is_user_defined = 1 AND
s.name = #Schema
ORDER BY s.name
SELECT #Sql = #Sql + 'DROP SCHEMA '+ QUOTENAME(#Schema) + ';' + CHAR(13)
EXECUTE sp_executesql #Sql
GO
Building on #Kevo's answer, I added the following for dropping all foreign key constraints before deleting the tables. I've only tested on SQL2008 R2
select #Sql = COALESCE(#Sql,'') + 'ALTER TABLE %SCHEMA%.' + t.name + ' drop constraint ' +
OBJECT_NAME(d.constraint_object_id) + ';' + CHAR(13)
from sys.tables t
join sys.foreign_key_columns d on d.parent_object_id = t.object_id
inner join sys.schemas s on t.schema_id = s.schema_id
where s.name = #Schema
ORDER BY t.name;
Also building on #Kevo's answer, I added the following while loop for an issue I was having with TSQL Print statement. A message string can be up to 8,000 characters long. If greater than 8,000 the print statement will truncate any remaining characters.
DECLARE #SqlLength int
, #SqlPosition int = 1
, #printMaxLength int = 8000
SET #SqlLength = LEN(#Sql)
WHILE (#SqlLength) > #printMaxLength
BEGIN
PRINT SUBSTRING(#Sql, #SqlPosition, #printMaxLength)
SET #SqlLength = #SqlLength - #printMaxLength
SET #SqlPosition = #SqlPosition + #printMaxLength
END
IF (#SqlLength) < #printMaxLength AND (#SqlLength) > 0
BEGIN
PRINT SUBSTRING(#Sql, #SqlPosition, #printMaxLength)
END
I combined the answers from #raider33 and #Kevo to one solutions for direct execution.
DECLARE #SqlStatement NVARCHAR(MAX)
DECLARE #schema varchar(30) = 'SCHEMA_NAME';
select #SqlStatement = COALESCE(#SqlStatement,'') + 'ALTER TABLE '+#schema+'.' + t.name + ' drop constraint ' +
OBJECT_NAME(d.constraint_object_id) + ';' + CHAR(13) + CHAR(10)
from sys.tables t
join sys.foreign_key_columns d on d.parent_object_id = t.object_id
inner join sys.schemas s on t.schema_id = s.schema_id
where s.name = #schema
ORDER BY t.name;
SELECT #SqlStatement +=
COALESCE(#SqlStatement, '') + 'DROP TABLE ' + #schema +'.'+ QUOTENAME(TABLE_NAME) + ';' + CHAR(13) + CHAR(10)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = #schema
EXECUTE sp_executesql #SqlStatement
Just in case it helps someone, I added this as a stored procedure to the master database to allow it to conveniently used on any db / schema.
It can be called like this:
EXEC master.dbo.dropTablesInSchema 'my_db', 'dbo
Stored procedure create script:
CREATE PROC [master].[dbo].[dropTablesInSchema]
#db nvarchar(max),
#schema nvarchar(max)
AS
BEGIN
DECLARE #Tables TABLE (name nvarchar(max))
INSERT INTO #Tables
EXEC ('SELECT TABLE_NAME FROM [' + #db + '].INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ''' + #schema + ''' and TABLE_TYPE =''BASE TABLE''')
DECLARE #SqlStatement NVARCHAR(MAX)
SELECT #SqlStatement =
COALESCE(#SqlStatement, N'') + N'DROP TABLE [' + #db + '].[' + #schema + '].' + QUOTENAME(NAME) + N';' + CHAR(13)
FROM #Tables
EXEC(#SqlStatement)
END
Building on chris LB's answer, I added
GROUP BY d.constraint_object_id, t.name
because I saw duplicate constraint deletions in my query. constraint_object_id is the FK Constraint ID, as noted at https://msdn.microsoft.com/en-us/library/ms186306.aspx
DECLARE #SqlStatement NVARCHAR(MAX),
#Schema NVARCHAR(20)
SET #Schema = 'aa'
SELECT #SqlStatement =
COALESCE(#SqlStatement,'') + 'ALTER TABLE '+#Schema+'.' + t.name + ' DROP CONSTRAINT ' +
OBJECT_NAME(d.constraint_object_id) + ';' + CHAR(13) + CHAR(10)
FROM sys.tables t
JOIN sys.foreign_key_columns d on t.object_id = d.parent_object_id
INNER JOIN sys.schemas s on t.schema_id = s.schema_id
WHERE s.name = #Schema
GROUP BY d.constraint_object_id, t.name
ORDER BY t.name;
select 'DROP TABLE [TABSCHEMA].' + QUOTENAME(TABLE_NAME) + N';' from INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'TABSCHEMA' and TABLE_TYPE = 'BASE TABLE'
This will generate all the DROP TABLE and DROP VIEW with check exists.
DECLARE #SqlStatement NVARCHAR(MAX)
SELECT #SqlStatement =
COALESCE(#SqlStatement, N'') + N'IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'''+'['+TABLE_SCHEMA+'].' + QUOTENAME(TABLE_NAME) +''' )' + CHAR(13)+
' DROP '+ TABLE_TYPE +' ['+TABLE_SCHEMA+'].' + QUOTENAME(TABLE_NAME) + N';' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA in ('SCHEMA1','SCHEMA2','SCHEMA13' )
ORDER BY TABLE_SCHEMA
PRINT REPLACE(#SqlStatement,'DROP BASE TABLE ','DROP TABLE ')
GO
Drop all tables in schema , can be modified to return any subset of tables.
declare #schema varchar(10) = 'temp'
declare #max_number_of_tables int = 1000
declare #sql nvarchar(max)
declare #index int = 0
while (
select count(*)
from
sys.objects obj
join sys.schemas s
on (s.schema_id=obj.schema_id)
where
s.name= #schema
and obj.type = 'U'
AND obj.is_ms_shipped = 0x0) > 0 and #index < #max_number_of_tables
begin
set #index = #index+1
select top 1
#sql = N'DROP TABLE [' + #schema + '].[' + obj.name + ']'
from
sys.objects obj
join sys.schemas s
on (s.schema_id=obj.schema_id)
where
s.name = #schema
and obj.type = 'U'
AND obj.is_ms_shipped = 0x0
order by obj.name
print #sql
execute(#sql)
end
Modification of acepted answer that works just copy pasted.
Change db to your database and set #dbSchema to your schema.
USE db -- CHANGE TO YOUR DB
GO
DECLARE #dbSchema NVARCHAR(200);
SET #dbSchema = 'dbo' -- CHANGE TO YOUR SCHEMA
DECLARE #SqlStatement NVARCHAR(MAX)
SELECT #SqlStatement =
COALESCE(#SqlStatement, N'') + N'DROP TABLE ' +'[' + #dbSchema +']' + '.' + QUOTENAME(TABLE_NAME) + N';' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = #dbSchema and TABLE_TYPE = 'BASE TABLE'
EXEC sp_executesql #SqlStatement