SQL Server : select columns of a table then select top 1 value - sql-server

Is there a way to select columns of a table then assign the top 1 value of that column.
For example
TABLENAME | COLUMNNAME | VALUE
----------+------------+---------------
TABLE 1 | COLUMN 1 | COLUMN 1 VALUE
TABLE 1 | COLUMN 2 | COLUMN 2 VALUE
UPDATE
DECLARE #tableCOLS TABLE (tablename varchar(255) , colname varchar(255));
BEGIN
SET #MyCursor = CURSOR FOR
SELECT DISTINCT tablename FROM #tableid
OPEN #MyCursor
FETCH NEXT FROM #MyCursor
INTO #MyField2
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #tableCOLS
SELECT #MyField2 , COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #MyField2
FETCH NEXT FROM #MyCursor
INTO #MyField2
END;
CLOSE #MyCursor ;
DEALLOCATE #MyCursor;
END;
SELECT * from #tableCOLS
END;
I fetch the table columns to my dynamic table then i want to insert the value of a certain data in the columns that i fetch in my table

I just tested this and it works a treat
DECLARE #Result TABLE (TableName VARCHAR(50), Col VARCHAR(50), MaxValue VARCHAR(50), MaxSQL NVARCHAR(4000));
DECLARE #TableName VARCHAR(50), #Col VARCHAR(50), #MaxSQL NVARCHAR(4000), #MaxValue VARCHAR(50)
-- Load all tables and columns of interest
INSERT INTO #Result
(TableName, Col, MaxSQL)
select
object_name(object_id),
name,
'SELECT #C = MAX(' + name + ') FROM ' + object_name(object_id)
from sys.columns where object_name(object_id) = 'Table1'
-- For each row, run the dynamic SQL and update back into table
DECLARE c CURSOR FOR
SELECT TableName, Col, MaxSQL FROM #Result
OPEN c
FETCH NEXT FROM C INTO #TableName, #Col, #MaxSQL
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC sp_ExecuteSQL #MaxSQL, N'#C VARCHAR(50) OUTPUT', #C = #MaxValue OUTPUT
UPDATE #Result SET MaxValue = #MaxValue WHERE TableName = #TableName AND Col = #Col;
FETCH NEXT FROM C INTO #TableName, #Col, #MaxSQL
END
CLOSE c;
DEALLOCATE c;
-- Show the results
SELECT * FROM #Result;

There's no need to use loops or cursors to do this. Have a look at the following...
SET NOCOUNT ON;
DECLARE #Object_id INT = OBJECT_ID('DataBaseName.Schema.TableName');
IF OBJECT_ID('tempdb..#TableCols', 'U') IS NOT NULL
DROP TABLE #TableCols;
CREATE TABLE #TableCols (
SchemaName sysname,
TableName sysname,
ColumnName sysname,
ColumnID INT NOT NULL,
Value NVARCHAR(MAX) NULL
);
INSERT #TableCols (SchemaName, TableName, ColumnName, ColumnID)
SELECT
s.name,
o.name,
c.name,
c.column_id
FROM
sys.objects o
JOIN sys.schemas s
ON o.schema_id = s.schema_id
JOIN sys.columns c
ON o.object_id = c.object_id
WHERE
o.type = 'U'
AND o.object_id = #Object_id
ORDER BY
c.column_id;
DECLARE
#CrossCols VARCHAR(MAX) = N'',
#TopVal NVARCHAR(10) = N'',
#Table sysname = N'',
#sql NVARCHAR(MAX) = N'',
#DeBug BIT = 0; -- 1 = PRINT ; 0 = EXECUTE
SELECT
#CrossCols = CONCAT(#CrossCols, N',
(', tc.ColumnID, N', CAST(t.[', tc.ColumnName, N'] AS NVARCHAR(MAX)))'),
#TopVal = tc.ColumnID,
#Table = CONCAT(tc.SchemaName, '.', tc.TableName)
FROM
#TableCols tc
ORDER BY
tc.ColumnID;
SET #sql = CONCAT(N'
UPDATE tc SET
tc.Value = t.ColumnValue
FROM
#TableCols tc
JOIN (
SELECT TOP (', #TopVal, N')
x.*
FROM
', #Table, N' t
CROSS APPLY ( VALUES', STUFF(#CrossCols, 1, 1, ''), N'
) x (ColumnID, ColumnValue)
) t
ON tc.ColumnID = t.ColumnID;')
IF #DeBug = 1
BEGIN
EXEC dbo.LongPrint #sql;
END;
ELSE
BEGIN
EXEC(#sql);
SELECT * FROM #TableCols tc;
END;

Give this a shot...
DECLARE #Table VARCHAR(MAX) = 'Customer'
SELECT t.name AS [Table]
, c.name AS [Column]
, cmd.mycmd
, TYPE_NAME(c.user_type_id) AS [Type]
, c.max_length AS [Size]
, CASE WHEN c.is_nullable = 1 THEN ''
ELSE 'No Nulls' END AS Nullable
, ROW_NUMBER() OVER ( PARTITION BY t.name ORDER BY c.name ASC ) AS rnk
, CASE WHEN EXISTS ( SELECT 1
FROM sys.columns c2
WHERE c2.object_id = t.object_id
AND c2.name IN ( SELECT *
FROM dbo.fnSplit('Fieldnames,ToSkip', ',') ) ) THEN 'Y'
ELSE 'N' END AS [CreModDeLs]
into #MyTempTable
FROM sys.columns AS c
JOIN sys.tables AS t ON c.object_id = t.object_id
cross apply (Select 'Select top 1 #Val = cast(' + c.name + ' as varchar(max)) from ' + t.name + ' Order by 1 desc' as mycmd) cmd
WHERE t.name LIKE #Table
ORDER BY t.name
, c.name
alter table #MyTempTable add [Id] integer identity(1,1)
alter table #MyTempTable add [Top1Val] Varchar(max)
Declare #DynamicSQL as nvarchar(1000);
Declare #dynamicparamdec nvarchar(1000) = '#val Varchar(max) Output'
Declare #valueofid as int
Declare #returnval as varchar(max)
Declare #Id integer
DECLARE #MyCursor CURSOR FAST_FORWARD
FOR
SELECT id
, mycmd
FROM #MyTempTable
where type <> 'image'
OPEN #MyCursor
FETCH #MyCursor INTO #id, #DynamicSQL
WHILE ##fetch_status = 0
BEGIN
print #dynamicsql
execute sp_executesql #DynamicSQL
, #dynamicparamdec
, #returnval output
update #MyTempTable
set Top1Val = #returnval
where id = #id
FETCH #MyCursor INTO #id, #DynamicSQL
END
--Close the cursor, if it is empty then deallocate it:
IF ( SELECT CURSOR_STATUS('global', '#MyCursor') ) >= -1
BEGIN
IF ( SELECT CURSOR_STATUS('global', '#MyCursor') ) > -1
BEGIN
CLOSE #MyCursor
END
DEALLOCATE #MyCursor
END
select * from #MyTempTable

Related

Way to select all columns from table and near each one the same column name with prefix?

Let's say I have a table with the following columns:
"col1", "col2", "col3", "new_col1", "new_col2", "new_col3" ...
I want to display the columns in the following way:
select col1, new_col1, col2, new_col2, col3, new_col3 ...
Is there a select command/keyboard shortcut that I can do that without copy each column in the select command
Thank you
I have a custom procedure mapped to Ctrl+8 shortcut.
It's something like that:
CREATE or ALTER PROC dbo.utl_get_select(
#table sysname,
#alias varchar(10) = 'v'
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #query varchar(max) = 'SELECT';
SELECT #alias = ISNULL(#alias, 'v')
SELECT #query = #query + ' ' + #alias + '.' + QUOTENAME(c.name)+','
FROM sys.objects t
JOIN sys.columns c ON c.object_id = t.object_id
WHERE t.name = #table
ORDER BY c.column_id ASC;
SELECT #query = LEFT(#query, LEN(#query)-1) + ' ';
SELECT #query + 'FROM dbo.' + #Table + ' ' + #alias;
END;
We could also use STRING_AGG in SQL Server 2017 or newer.
You can also compare columns names to achieve some customised order.
And the result for EXEC dbo.utl_get_select 'users'
SELECT v.[id], v.[login], v.[email], v.[name], v.[last_name] FROM dbo.users v
Here is a script for Insert and Select
DECLARE #String nvarchar(max)='',#Column nvarchar(100),#Insert nvarchar(max), #Select nvarchar(max),#TBL_NAME nvarchar(150)
SET #TBL_NAME = 'TestTable'
DECLARE CURS CURSOR LOCAL FAST_FORWARD FOR
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = #TBL_NAME
OPEN CURS
FETCH NEXT FROM CURS INTO #Column
WHILE ##FETCH_STATUS=0
BEGIN
SET #String = #String +'['+#Column+'],'+'['+#Column+'_NEW],'
FETCH NEXT FROM CURS INTO #Column
END
CLOSE CURS
DEALLOCATE CURS
SET #String = SUBSTRING(#String,1,LEN(#String)-1)
SET #Insert = 'INSERT INTO ['+#TBL_NAME+'] ('+#String+')'
SET #Select = 'SELECT '+#String
Select #Insert,#Select

i use two cursor for this. but i want to minimize it to one cursor

declare #tab_name varchar(100)
declare #col_name varchar(100)
declare #sqlquery nvarchar(max)
declare cursor_table cursor
for
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES --where table_name!='tab'
open cursor_table
fetch next from cursor_table into #tab_name
while ##fetch_status = 0
begin
declare cursor_count cursor
for
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #tab_name
open cursor_count
fetch next from cursor_count into #col_name
while ##FETCH_STATUS =0
begin
set #sqlquery='
select '+''''+#tab_name+''''+','+''''+ #col_name+''''+',count('+#col_name+') as count from '+#tab_name+' where ISNULL('+#col_name+','''') !='''' '
print #sqlquery
exec sp_executesql #sqlquery
fetch next from cursor_count into #col_name
End
CLOSE cursor_count
DEALLOCATE cursor_count
print #tab_name
fetch next from cursor_table into #tab_name
end
CLOSE cursor_table
DEALLOCATE cursor_table
I would approach it this way if I "needed" to get a count of all null values per column, per table.
This is very inefficient query and may take a while to execute as you are bound to perform multiple full table scans for all non-indexed fields. I would advise, for this exercise, that you limit it to a few tables.
SELECT CommandOrder=1,'DECLARE #TEMP TABLE(TableName NVARCHAR(100), ColumnName NVARCHAR(100), NullRecordCount INT)'
UNION
SELECT CommandOrder=3,
'INSERT #TEMP SELECT '''+S.Name+'.'+T.Name+''','''+C.Name+''', COUNT(*) FROM '+S.Name+'.'+T.Name+' WHERE COALESCE('+C.Name+',NULL)=NULL'
FROM
SYS.Columns C
INNER JOIN SYS.Tables T ON C.object_id = T.object_id
INNER JOIN SYS.Schemas S ON T.schema_id = S.schema_id
UNION
SELECT CommandOrder=4,'SELECT * FROM #TEMP T WHERE NullRecordCount > 0 ORDER BY TableName,ColumnName'
If it is a requirement to minimize it to one cursor at the very least, use this.
If you really have to use cursors, use FAST_FORWARD cursor option.
declare #tab_name varchar(100)
declare #col_name varchar(100)
declare #sqlquery nvarchar(max)
DECLARE #mainTable TABLE(
Id INT IDENTITY(1,1) PRIMARY KEY,
TABLE_NAME Varchar(500)
)
--GET TABLES data into main table
INSERT INTO #mainTable
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
DECLARE #startTables INT = 1
DECLARE #finalTables INT = 0
SELECT #finalTables = MAX(Id) FROM #mainTable
-- Do a while loop over id
WHILE #startTables <= #finalTables
BEGIN
-- Get the table name
SELECT #tab_name = TABLE_NAME FROM #mainTable WHERE Id = #startTables
-- Initialize cursor
declare cursor_count cursor
for
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = #tab_name
open cursor_count
fetch next from cursor_count into #col_name
while ##FETCH_STATUS =0
begin
set #sqlquery='select '+''''+#tab_name+''''+','+''''+ #col_name+''''+',count('+#col_name+') as count from '+#tab_name+' where ISNULL('+#col_name+','''') !='''' '
print #sqlquery
exec sp_executesql #sqlquery
fetch next from cursor_count into #col_name
End
CLOSE cursor_count
DEALLOCATE cursor_count
print #tab_name
SET #startTables = #startTables + 1
END
To use no cursor at all, use this.
declare #tab_name varchar(100)
declare #col_name varchar(100)
declare #sqlquery nvarchar(max)
-- Table stores Id, table name, Query in one go.
DECLARE #secondaryTable TABLE(
Id INT IDENTITY(1,1) PRIMARY KEY,
TABLE_NAME Varchar(500),
Query Varchar(8000)
)
INSERT INTO #secondaryTable
SELECT a.TABLE_NAME, 'select '+''''+a.TABLE_NAME+''''+','+''''+ b.COLUMN_NAME+''''+',count('+b.COLUMN_NAME+') as count from '+a.TABLE_NAME+' where ISNULL('+b.COLUMN_NAME+','''') !='''' '
FROM INFORMATION_SCHEMA.TABLES a INNER JOIN INFORMATION_SCHEMA.COLUMNS b ON a.TABLE_NAME = b.TABLE_NAME
--SELECT * FROM #secondaryTable
DECLARE #startTables INT = 1
DECLARE #finalTables INT = 0
SELECT #finalTables = MAX(Id) FROM #secondaryTable
-- Loop through the table, get the table name and query. Execute the query.
WHILE #startTables <= #finalTables
BEGIN
SELECT #tab_name = TABLE_NAME, #sqlquery = Query FROM #secondaryTable WHERE Id = #startTables
print #sqlquery
exec sp_executesql #sqlquery
print #tab_name
SET #startTables = #startTables + 1
END

SQL : Server dynamic PIVOT query

I am trying to make the below Pivot SQL query dynamic.
List of the dynamic customer should be retrieved from below query.
Customer List Query
SELECT
Cust_Name
FROM dbo.Customer
INNER JOIN dbo.Service
ON dbo.Customer.Cust_ID = dbo.Service.Cust_ID
WHERE [Next_Service] BETWEEN '2017-09-01' AND '2015-09-10'
Pivot query
Select *
from
(
select Customer.Cust_Name,Agreementlist.ProductQty,Store.Product_Name as Refill
from dbo.Agreement INNER JOIN dbo.Agreementlist ON dbo.Agreement.Agreement_ID = dbo.Agreementlist.Agreement_ID INNER JOIN dbo.Customer
ON dbo.Customer.Cust_ID = dbo.Agreement.Cust_ID INNER JOIN Store on Store.Pro_ID = dbo.Agreementlist.ProID where CatID='2' and Agreement.Status='Approved'
) x
pivot
(
sum(ProductQty)
for Cust_Name in ("list of customers resulted from the first query")
) p
You can add a cursor to loop over your customers and add them to a variable. This here works.
declare #gruppe nvarchar(max)
declare #gruppeSql nvarchar(max)
declare #SQL nvarchar(max)
DECLARE myCustomers CURSOR FOR
SELECT Cust_Name FROM dbo.Customer INNER JOIN dbo.Service
ON dbo.Customer.Cust_ID = dbo.Service.Cust_ID
WHERE [Next_Service] BETWEEN '2017-09-01' AND '2015-09-10'
set #gruppeSql = ''
OPEN myCustomers
FETCH NEXT FROM myCustomers INTO #gruppe
IF (##FETCH_STATUS>=0)
BEGIN
SET #gruppeSql = #gruppeSql +'[' +#gruppe+']'
FETCH NEXT FROM myCustomers INTO #gruppe
END
WHILE (##FETCH_STATUS<>-1)
BEGIN
IF (##FETCH_STATUS<>-2)
SET #gruppeSql = #gruppeSql + ',[' +#gruppe+']'
FETCH NEXT FROM myCustomers INTO #gruppe
END
CLOSE myCustomers
DEALLOCATE myCustomers
SET #gruppeSql = replace(#gruppesql,'''','')
--select #gruppeSql
SET #SQL = '
Select *
from
(
select Customer.Cust_Name,Agreementlist.ProductQty,Store.Product_Name as
Refill
from dbo.Agreement INNER JOIN dbo.Agreementlist ON
dbo.Agreement.Agreement_ID = dbo.Agreementlist.Agreement_ID INNER JOIN
dbo.Customer
ON dbo.Customer.Cust_ID = dbo.Agreement.Cust_ID INNER JOIN Store on
Store.Pro_ID = dbo.Agreementlist.ProID where CatID=''2'' and
Agreement.Status=''Approved''
) x
pivot
(
sum(ProductQty)
for Cust_Name in ('+#gruppesql+')
) p'
print #sql
exec(#sql)
SQL Print
Result:
I have used this SQL script to create dynamic Pivot
CREATE PROCEDURE [dbo].[dynamicPivot]
(#tablename VARCHAR(250),
#pivotColumn VARCHAR(250),
#groupBy VARCHAR(8000),
#aggregateColumns VARCHAR(250),
#aggregation VARCHAR(250),
#execute INT = 0
)
AS
BEGIN
DECLARE #sql VARCHAR(8000), #pivotcols VARCHAR(8000)= '';
DECLARE #result TABLE(result VARCHAR(8000));
SET #sql = '
declare
#pivotcols varchar(8000) = '''';
with cte as (
select distinct '+#pivotColumn+', ''[''+cast('+#pivotColumn+' as varchar(250))+'']'' col
from '+#tablename+')
select #pivotcols = #pivotcols + col + '',''
from cte
order by '+#pivotColumn+';
set #pivotcols = left(#pivotcols, len(#pivotcols)-1);
select #pivotcols result';
INSERT INTO #result
EXEC (#sql);
SELECT #pivotcols = result
FROM #result;
SET #sql = '
SELECT *
FROM (
SELECT
'+#groupBy+CASE #groupBy
WHEN ''
THEN ''
ELSE ', '
END+#pivotColumn+', '+#aggregateColumns+'
FROM '+#tablename+'
) AS s
PIVOT
(
'+#aggregation+'
FOR '+#pivotColumn+' IN ('+#pivotcols+')
)AS p;';
IF #execute = 0
PRINT(#sql);
ELSE
EXEC (#sql);
END;
GO

create sql view from a sql function

I have a function that will return all items in all firms.Table names should be parametric.But I could not create a view from that function.Because I can not return a table.The returned value is a string. Please help.Thanks.
GO
IF OBJECT_ID(N'dbo.ufnGetContactInformation', N'TF') IS NOT NULL
DROP FUNCTION dbo.ufnGetContactInformation;
GO
CREATE FUNCTION dbo.ufnGetContactInformation()
RETURNS #retContactInformation TABLE
(
-- Columns returned by the function
firm nvarchar(50) NULL
)
AS
BEGIN
DECLARE #referans AS INT, #NRP AS INT
DECLARE #TABLE AS NVARCHAR(MAX)
SET #TABLE = ''
DECLARE YourCursorNameHere CURSOR READ_ONLY
FOR
select c1.NR, C2.NR
from L_caPIFIRM c1 WITH(nolock)
INNER JOIN L_CAPIPERIOD C2 WITH(nolock) ON C1.NR=C2.FIRMNR
OPEN YourCursorNameHere
FETCH NEXT FROM YourCursorNameHere INTO #referans, #NRP
WHILE ##FETCH_STATUS = 0
BEGIN
IF #TABLE = ''
SET #TABLE= 'SELECT FIRM=' + str(#referans) +', CODE FROM LG_' + SUBSTRING(('00'+ LTRIM(STR(#referans))),LEN(('00'+ LTRIM(STR(#referans))))-2,3)+ '_ITEMS'
ELSE
SET #TABLE= #TABLE + ' UNION SELECT FIRM=' + str(#referans) +', CODE FROM LG_' + SUBSTRING(('00'+ LTRIM(STR(#referans))),LEN(('00'+ LTRIM(STR(#referans))))-2,3)+ '_ITEMS'
FETCH NEXT FROM YourCursorNameHERE INTO #referans,#NRP
END
-- EXEC( #TABLE)
CLOSE YourCursorNameHere
DEALLOCATE YourCursorNameHere
--BEGIN
-- INSERT INTO select
-- END
RETURN;
END;
GO
Try to use dynamic sql .I didnt check it but maybe this is the way to do it...
RETURNS #retContactInformation varchar(max) -- not table
.
.
DECLARE #sql nvarchar(max)
DECLARE #sqlx nvarchar(max)=dbo.ufnGetContactInformation()
set #sql='CREATE VIEW [aaa]
AS
'+ #sqlx+''
EXECUTE sp_executesql #SQL
instead of cursor try while loop
CREATE TABLE #tempo (id INT IDENTITY (1,1),c1nr varchar(10),c2nr varchar(10))
insert into #tempo
select c1.NR, C2.NR
from L_caPIFIRM c1 WITH(nolock)
INNER JOIN L_CAPIPERIOD C2 WITH(nolock) ON C1.NR=C2.FIRMNR
DECLARE #i int = (SELECT count(*) FROM #tempo)
DECLARE #id int=1
WHILE #i!=0
BEGIN
SELECT #referans=c1nr,
#table =IIF ((#TABLE = ''),
'SELECT FIRM=' + str(#referans) +', CODE FROM LG_' + SUBSTRING(('00'+ LTRIM(STR(#referans))),LEN(('00'+ LTRIM(STR(#referans))))-2,3)+ '_ITEMS',
#TABLE + ' UNION SELECT FIRM=' + str(#referans) +', CODE FROM LG_' + SUBSTRING(('00'+ LTRIM(STR(#referans))),LEN(('00'+ LTRIM(STR(#referans))))-2,3)+ '_ITEMS' )
from #tmpo
where id=#id
set #id=#id+1
set #i=#i-1
END

Drop all objects in SQL DB?

Does anyone have a script that will drop all objects in a SQL Server DB?
I currently don't have rights to drop and create DBs on the server so am looking for a script to take me back to 'square one'
I've seen some on the web, but they don't do things in the right order or they don't remove everything.
If you use schemas you may find the following script useful:
SET NOCOUNT ON;
DECLARE #OnlyInSchema sysname;
-- Set this to a value to only drop objects in one schema.
-- SET #OnlyInSchema = N'';
DECLARE #Commands TABLE (
[Description] NVARCHAR(MAX),
[Line] NVARCHAR(MAX)
);
DECLARE #Drops TABLE (
[Type] NVARCHAR(2),
[Template] NVARCHAR(MAX)
);
-- -- -- -- -- OBJECTS NOT ASSOCIATED WITH TABLES -- -- -- -- --
INSERT INTO #Drops
SELECT N'AF', N'DROP AGGREGATE $S.$O;' UNION
SELECT N'FN', N'DROP FUNCTION $S.$O;' UNION
SELECT N'FS', N'DROP FUNCTION $S.$O;' UNION
SELECT N'FT', N'DROP FUNCTION $S.$O;' UNION
SELECT N'IF', N'DROP FUNCTION $S.$O;' UNION
SELECT N'P', N'DROP PROCEDURE $S.$O;' UNION
SELECT N'SN', N'DROP SYNONYM $S.$O;' UNION
SELECT N'SQ', N'DROP QUEUE $S.$O;' UNION
SELECT N'TR', N'DROP TRIGGER $S.$O;' UNION
SELECT N'TT', N'DROP TYPE $S.$O;' UNION
SELECT N'TF', N'DROP FUNCTION $S.$O;';
INSERT INTO #Commands
SELECT QUOTENAME(RTRIM([S].[name])) + '.' + QUOTENAME(RTRIM([O].[name])),
REPLACE(REPLACE([D].[Template], '$S', QUOTENAME(RTRIM([S].[name]))), '$O', QUOTENAME(RTRIM([O].[name])))
FROM [sys].[objects] AS [O]
INNER JOIN [sys].[schemas] AS [S] ON [O].[schema_id] = [S].[schema_id]
INNER JOIN #Drops AS [D] ON [O].[type] COLLATE Latin1_General_CS_AS = [D].[Type] COLLATE Latin1_General_CS_AS
WHERE (#OnlyInSchema IS NULL OR [S].[name] COLLATE Latin1_General_CS_AS = #OnlyInSchema)
AND [S].[name] COLLATE Latin1_General_CS_AS <> 'sys'
AND [O].[is_ms_shipped] = 0;
-- -- -- -- -- OBJECTS ASSOCIATED WITH TABLES -- -- -- -- --
DELETE FROM #Drops;
INSERT INTO #Drops
SELECT N'C', N'ALTER TABLE $TS.$TO DROP CONSTRAINT $O;' UNION
SELECT N'D', N'ALTER TABLE $TS.$TO DROP CONSTRAINT $O;' UNION
SELECT N'F', N'ALTER TABLE $TS.$TO DROP CONSTRAINT $O;' UNION
SELECT N'PK', N'ALTER TABLE $TS.$TO DROP CONSTRAINT $O;';
INSERT INTO #Commands
SELECT QUOTENAME(RTRIM([S].[name])) + '.' + QUOTENAME(RTRIM([PO].[name])) + '::' + QUOTENAME(RTRIM([O].[name])),
REPLACE(REPLACE(REPLACE([D].[Template], '$TS', QUOTENAME(RTRIM([S].[name]))), '$O', QUOTENAME(RTRIM([O].[name]))), '$TO', QUOTENAME(RTRIM([PO].[name])))
FROM [sys].[objects] AS [O]
INNER JOIN [sys].[objects] AS [PO] ON [O].[parent_object_id] = [PO].[object_id]
INNER JOIN [sys].[schemas] AS [S] ON [PO].[schema_id] = [S].[schema_id]
INNER JOIN #Drops AS [D] ON [O].[type] COLLATE Latin1_General_CS_AS = [D].[Type] COLLATE Latin1_General_CS_AS
WHERE (#OnlyInSchema IS NULL OR [S].[name] COLLATE Latin1_General_CS_AS = #OnlyInSchema)
AND [S].[name] COLLATE Latin1_General_CS_AS <> 'sys'
AND [O].[is_ms_shipped] = 0;
-- -- -- -- -- ACTUAL DROP -- -- -- -- --
DELETE FROM #Drops;
INSERT INTO #Drops
SELECT N'U', N'DROP TABLE $S.$O;' UNION
SELECT N'V', N'DROP TABLE $S.$O;';
INSERT INTO #Commands
SELECT QUOTENAME(RTRIM([S].[name])) + '.' + QUOTENAME(RTRIM([O].[name])),
REPLACE(REPLACE([D].[Template], '$S', QUOTENAME(RTRIM([S].[name]))), '$O', QUOTENAME(RTRIM([O].[name])))
FROM [sys].[objects] AS [O]
INNER JOIN [sys].[schemas] AS [S] ON [O].[schema_id] = [S].[schema_id]
INNER JOIN #Drops AS [D] ON [O].[type] COLLATE Latin1_General_CS_AS = [D].[Type] COLLATE Latin1_General_CS_AS
WHERE (#OnlyInSchema IS NULL OR [S].[name] COLLATE Latin1_General_CS_AS = #OnlyInSchema)
AND [S].[name] COLLATE Latin1_General_CS_AS <> 'sys'
AND [O].[is_ms_shipped] = 0;
-- -- -- -- -- TABLES -- -- -- -- --
DECLARE #Description NVARCHAR(MAX);
DECLARE #Message NVARCHAR(MAX);
DECLARE #Command NVARCHAR(MAX);
DECLARE CommandCursor CURSOR FOR
SELECT [Description], [Line] FROM #Commands;
OPEN CommandCursor;
FETCH NEXT FROM CommandCursor INTO #Description, #Command;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #Message = N'Dropping ' + #Description + '...';
PRINT #Message;
BEGIN TRY
EXEC sp_executesql #Command;
END TRY
BEGIN CATCH
SET #Message = N'Failed to drop ' + #Description + ':';
PRINT #Message;
PRINT ERROR_MESSAGE()
END CATCH
FETCH NEXT FROM CommandCursor INTO #Description, #Command;
END
CLOSE CommandCursor;
DEALLOCATE CommandCursor;
I found this code on "http://kashyapmakadia.blogspot.com/2009/08/drop-everything-in-sql-server-2005.html" and tried it and it worked just find!! You can find the code there, but if you're in hurry, the code is:
/* Drop all non-system stored procs */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])
WHILE #name is not null
BEGIN
SELECT #SQL = 'DROP PROCEDURE [' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Procedure: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > #name ORDER BY [name])
END
GO
/* Drop all views */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP VIEW [' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped View: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > #name ORDER BY [name])
END
GO
/* Drop all functions */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP FUNCTION [' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Function: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > #name ORDER BY [name])
END
GO
/* Drop all Foreign Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
WHILE #name is not null
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
WHILE #constraint IS NOT NULL
BEGIN
SELECT #SQL = 'ALTER TABLE [' + RTRIM(#name) +'] DROP CONSTRAINT ' + RTRIM(#constraint)
EXEC (#SQL)
PRINT 'Dropped FK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE #name VARCHAR(128)
DECLARE #constraint VARCHAR(254)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
WHILE #name IS NOT NULL
BEGIN
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
WHILE #constraint is not null
BEGIN
SELECT #SQL = 'ALTER TABLE [' + RTRIM(#name) +'] DROP CONSTRAINT ' + RTRIM(#constraint)
EXEC (#SQL)
PRINT 'Dropped PK Constraint: ' + #constraint + ' on ' + #name
SELECT #constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> #constraint AND TABLE_NAME = #name ORDER BY CONSTRAINT_NAME)
END
SELECT #name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all tables */
DECLARE #name VARCHAR(128)
DECLARE #SQL VARCHAR(254)
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])
WHILE #name IS NOT NULL
BEGIN
SELECT #SQL = 'DROP TABLE [' + RTRIM(#name) +']'
EXEC (#SQL)
PRINT 'Dropped Table: ' + #name
SELECT #name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > #name ORDER BY [name])
END
GO
You can try the open-source bsn ModuleStore versioning toolkit, which can create an inventory of a database and create a DROP script for a database schema which respects the dependencies of the objects. It currently supports tables, indexes, triggers, views, functions, stored procedures and XML schema collections.
using (ManagementConnectionProvider provider = new ManagementConnectionProvider(connection, "dbo")) {
DatabaseInventory inventory = new DatabaseInventory(provider, "dbo");
string dropScript = string.Join(";\r\nGO\r\n\r\n", inventory.GenerateUninstallSql().ToArray());
}
Select * From sysobjects Where....
Then drop one by one.

Resources