Drop multiple tables with string - sql-server

I have tables like lg-010-a..., lg-010-ac..., and so on, I have abc database,
I have a command window:
drop table from abc where Table_Name like 'lg-010-%'
Will this drop all the tables starting with lg-010-?

Try something like this:
declare #sql varchar(max)
declare #tablenames varchar(max)
select #tablenames = coalesce(#tablenames + ', ','') + Table_Name from INFORMATION_SCHEMA.TABLES
where Table_Name like ('lg-010-%')
set #sql = 'drop table ' + #tablenames
exec (#sql)
This queries the INFORMATION_SCHEMA.TABLES table to retrieve table names that match your criteria, then concatenates them together into a comma delimited string.
This string is than added to a 'Drop table ' statement and executed.
Drop table can take multiple comma delimited table names.
(I had originally had this query sys.tables but some research revealed that while they are currently equivalent, the Information_Schema method is quaranteed to work in future versions)

Unfortunately you can't do it like that. One way is:
SELECT 'DROP TABLE ' + name FROM sysobjects WHERE name LIKE '%lg-010-a%' AND [type] IN ('P')
This will just print out the DROP TABLE statement for each table - you can then copy and paste this output and run it. You can just put an EXECUTE in the loop instead of the PRINT, but I've done it this way so you can see what's going on/check the output first.

I had an issue where the accepted answer was not doing anything. I discovered that I had to add the prefix name of the database to the code to get it to work. If your tables are not dbo.tablename try this.
declare #sql varchar(max)
declare #tablenames varchar(max)
SELECT
#tablenames = COALESCE(#tablenames + ', ','') + 'YourDatabaseName.' + Table_Name
FROM
INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME LIKE 'AP2%'
AND (RIGHT(TABLE_NAME, 6) < 201708)
SET #sql = 'drop table ' + #tablenames
EXEC (#sql)
GO

Unfortunately you can't do it like that.
One way is:
DECLARE #TableName NVARCHAR(128)
SELECT TOP 1 #TableName = TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'lg-010-%'
ORDER BY TABLE_NAME ASC
WHILE (##ROWCOUNT > 0)
BEGIN
PRINT 'DROP TABLE [' + #TableName + ']'
SELECT TOP 1 #TableName = TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'lg-010-%'
AND TABLE_NAME > #TableName
ORDER BY TABLE_NAME ASC
END
This will just print out the DROP TABLE statement for each table - you can then copy and paste this output and run it. You can just put an EXECUTE in the loop instead of the PRINT, but I've done it this way so you can see what's going on/check the output first.

CREATE PROCEDURE dbo.drop_MsSqlTables1 #createDate smalldatetime
AS
declare #flag int =1
declare #tname varchar(50)
declare #sql varchar(max)
select row_number() over (order by name) as num, '[dbo].[' + name +']' as table_name into #temp from sys.tables where name like ('EmpInfo_%') and create_date<#createDate
declare #count int = (select count(*) from #temp)
select * from #temp
while #flag <= #count
begin
set #tname = (select table_name from #temp where num = #flag)
set #sql = 'drop table ' + #tname
exec (#sql)
set #flag = #flag+1
end

Related

Alter tables in a schema

I am trying to set a default value to a column(Inserted_time), but first i need to check if the column exists in the tables. If the column doesn't exist, I need to add that column and give it a default value.
I am working with Sql Server Management Studio.
So far I have written this code:
IF EXISTS ( select TABLE_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG = 'DB_COPY' and COLUMN_NAME = 'Inserted_Time')
begin
ALTER TABLE table_name ADD CONSTRAINT [Inserted_Time_Def] SET DEFAULT (sysdatetimeoffset()) FOR [Inserted_Time]
end
else
ALTER TABLE table_name ADD COLUMN [Inserted_Time] CONSTRAINT [Inserted_Time_Def] DEFAULT (sysdatetimeoffset()) WITH VALUES
Once I retrieve the tables that has the column, I need to add that table_name to the Alter command. But I am not able to do that. Can someone please tell me how to use the table_names retrieved from select statement in the alter statement?
First, you want to put all the table names in a temporary table so you can loop through it.
After, you can use a cursor to execute a command for each table name.
In my example, I only printed the command I wanted to execute. That way you can be sure the code will do what you want first.
Example :
select TABLE_NAME As TableName INTO #TablesList from INFORMATION_SCHEMA.COLUMNS where TABLE_CATALOG = 'DB_COPY' and COLUMN_NAME = 'Inserted_Time'
DECLARE #TablesCursor as CURSOR;
DECLARE #TableName as NVARCHAR(max);
DECLARE #CommandToExecute as NVARCHAR(max);
SET #TablesCursor = CURSOR FOR SELECT TableName FROM #TablesList;
OPEN #TablesCursor;
FETCH NEXT FROM #TablesCursor INTO #TableName;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #CommandToExecute = 'ALTER TABLE ' + #TableName + ' WHAT YOU WANNA DO '
PRINT #CommandToExecute
--EXEC(#CommandToExecute)
FETCH NEXT FROM #TablesCursor INTO #TableName;
END
CLOSE #TablesCursor;
DEALLOCATE #TablesCursor;
Assuming that every table is in a different schema, then you could do something like this:
DECLARE #SQL nvarchar(MAX);
SET #SQL = STUFF((SELECT NCHAR(13) + NCHAR(10) +
CASE WHEN EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS C
WHERE T.TABLE_SCHEMA = C.TABLE_SCHEMA
AND T.TABLE_NAME = C.TABLE_SCHEMA
AND C.COLUMN_NAME = N'Inserted_Time') THEN N'ALTER TABLE ' + QUOTENAME(T.TABLE_SCHEMA) + N'.' + QUOTENAME(T.TABLE_NAME) + N' ADD CONSTRAINT [Inserted_Time_Def] DEFAULT (sysdatetimeoffset()) FOR [Inserted_Time];'
ELSE N'ALTER TABLE ' + QUOTENAME(T.TABLE_SCHEMA) + N'.' + QUOTENAME(T.TABLE_NAME) + N' ADD COLUMN [Inserted_Time] CONSTRAINT [Inserted_Time_Def] DEFAULT (sysdatetimeoffset());'
END
FROM INFORMATION_SCHEMA.TABLES T
WHERE T.TABLE_CATALOG = N'DB_COPY'
FOR XML PATH(N''),TYPE).value('.','nvarchar(MAX)'),1,2,N'');
PRINT #SQL; --Your best friend. If more than 4,000 characters, use SELECT
EXECUTE sp_executesql #SQL;
This will very likely hugely out perform a CURSOR solution if you have a large number of schemas.

How to make table truncation query as dynamic SQL

I would like to make the below query as dynamic SQL .
Query 1 : Table Truncation
select 'Truncate Table '+''+ name from sys.tables where name like '%RND%'
Query 2 :
select 'Insert into '+''+ name +'Select * from '+'.'+''+ name from sys.tables where name like '%RND%'
By using the following dynamic query you can truncate the required tables:
DECLARE #DynamicSQL AS VARCHAR(MAX) = '';
SELECT #DynamicSQL = #DynamicSQL + 'TRUNCATE TABLE ' + QUOTENAME(NAME) + '; '
FROM sys.tables
WHERE NAME LIKE '%RND%';
--PRINT #DynamicSQL
EXEC (#DynamicSQL)
For the second query the dynamic query is :
DECLARE #DynamicSQL1 AS VARCHAR(MAX) = '';
SELECT #DynamicSQL1 = #DynamicSQL1 + 'INSERT INTO ' + QUOTENAME(NAME) + ' SELECT * FROM ' + QUOTENAME(NAME) + '; '
FROM sys.tables
WHERE NAME LIKE '%RND%';
--PRINT #DynamicSQL1
EXEC (#DynamicSQL1)
This might be what you are looking for
All statements are collected in a table, ordered by their point of insert (id is IDENTITY). It will be - for sure - no problem for you to build your second statement in the same way...
DECLARE #cmdTbl TABLE(id INT IDENTITY,cmd NVARCHAR(MAX));
INSERT INTO #cmdTbl(cmd)
SELECT 'TRUNCATE TABLE ' + QUOTENAME(t.TABLE_CATALOG) + '.' + QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME) + ';'
FROM INFORMATION_SCHEMA.TABLES AS t
WHERE t.TABLE_NAME LIKE '%RND%'
--After collecting all statements I use a CURSOR to execute them one after the other.
DECLARE #cmd VARCHAR(MAX);
DECLARE cur CURSOR FOR SELECT cmd FROM #cmdTbl ORDER BY id;
OPEN cur;
FETCH NEXT FROM cur INTO #cmd;
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT #cmd;
--EXEC(#cmd); --For syntax check you start without EXEC...
FETCH NEXT FROM cur INTO #cmd;
END
CLOSE cur;
DEALLOCATE cur;
Step 1:
vi truncate_count.sql
use dbname
go
---generate truncate table statements
select 'Truncate Table '+''+convert(varchar(30),o.name)+'
go' as table_name
from sysobjects o
where type = 'U'
order by table_name
go
---check the table count
select 'select count(1) from '+''+convert(varchar(30),o.name)+'
go' AS table_name
from sysobjects o
where type = 'U'
order by table_name
go
Step 2:
isql -U<USER> -S<server> -P<pwd> -w999 -D<dbname> -e -itruncate_count.sql -otruncate_count1.sql
Step 3:
Add the below lines at the starting of the file truncate_count1.sql
use dbname
go
isql -U<USER> -S<server> -P<pwd> -w999 -D<dbname> -e -itruncate_count1.sql -otruncate_count1.log

Search for a string in all databases, all columns, and all tables (SQL Server 2008 R2)

We suffered some kind of invasion in our SQL Server.
I'm trying to find in every database, in every table, every column the word abortion and cheat.
I can do this with this query, but in a single database.
-- Store results in a local temp table so that. I'm using a
-- local temp table so that I can access it in SP_EXECUTESQL.
create table #tmp
(
db varchar(max),
tbl nvarchar(max),
col nvarchar(max),
val nvarchar(max),
);
declare #db nvarchar(max);
declare #tbl nvarchar(max);
declare #col nvarchar(max);
declare #q nvarchar(max);
declare #search nvarchar(max) = 'abortion';
-- Create a cursor on all columns in the database
declare c cursor for
SELECT
DB_NAME(DB_ID()) as DBName, tbls.TABLE_NAME, cols.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLES AS tbls
JOIN INFORMATION_SCHEMA.COLUMNS AS cols ON tbls.TABLE_NAME = cols.TABLE_NAME
-- For each table and column pair, see if the search value exists.
open c
fetch next from c into #db, #tbl, #col
while ##FETCH_STATUS = 0
begin
-- Look for the search key in current table column and if found add it to the results.
SET #q = 'INSERT INTO #tmp SELECT ''' +#db+''',''' + #tbl + ''', ''' + #col + ''', ' + #col + ' FROM ' + #tbl + ' WHERE ' + #col + ' LIKE ''%' + #search + '%'''
EXEC SP_EXECUTESQL #q
fetch next from c into #db, #tbl, #col
end
close c
deallocate c
-- Get results
select distinct db,tbl,col from #tmp
-- Remove local temp table.
drop table #tmp
How can I find these strings? The result set should be:
DATABASE | TABLE | COLUMN
I don't need the result ( text field ), and I need to select distinct for tables and columns, because it will be a lot of abortion in the same table/column.
While the use of the undocumented sp_msforeachdb is generally not encouraged, my instinct would be to send your existing code to this procedure like this:
exec sp_MSforeachdb 'USE [?];
-- Store results in a local temp table so that. I'm using a
-- local temp table so that I can access it in SP_EXECUTESQL.
create table #tmp (
db varchar(max) ,
tbl nvarchar(max),
col nvarchar(max),
val nvarchar(max),
);
declare #db nvarchar(max);
declare #tbl nvarchar(max);
declare #col nvarchar(max);
declare #q nvarchar(max);
--------------------------------------------------------------------------------------------
declare #search nvarchar(max) = ''abortion'';
--------------------------------------------------------------------------------------------
-- Create a cursor on all columns in the database
declare c cursor for
SELECT DB_NAME(DB_ID()) as DBName,tbls.TABLE_NAME, cols.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLES AS tbls
JOIN INFORMATION_SCHEMA.COLUMNS AS cols
ON tbls.TABLE_NAME = cols.TABLE_NAME
-- For each table and column pair, see if the search value exists.
open c
fetch next from c into #db, #tbl, #col
while ##FETCH_STATUS = 0
begin
-- Look for the search key in current table column and if found add it to the results.
SET #q = ''INSERT INTO #tmp SELECT '''''' +#db+'''''','''''' + #tbl + '''''', '''''' + #col + '''''', '' + #col + '' FROM '' + #tbl + '' WHERE '' + #col + '' LIKE ''''%'' + #search + ''%''''''
EXEC SP_EXECUTESQL #q
fetch next from c into #db, #tbl, #col
end
close c
deallocate c;'
The only added code here is the first line, for the rest of the code just make sure to replace ' with ''. The ? in USE [?] is a special character meaning the currently active database in the loop sp_MSforeachdb executes.

Trying to write some T-SQL to iterate through the DB tables

I am using SQL Server 2008 R2 on dev, and SQL Azure for test and live.
I wish to write a little procedure to reset the identity seeds since SQL Azure does not support DBCC.
I have some workaround code which works, but I do not want to write it out for each table, so was trying to write a routine that iterates through the DB tables.
Tables:
SELECT * FROM information_schema.tables
Code:
delete from TABLE_NAME where Id>150000
GO
SET IDENTITY_INSERT [TABLE_NAME] ON
GO
INSERT INTO [TABLE_NAME](Id) VALUES(150000)
GO
delete from TABLE_NAME where Id=150000
GO
SET IDENTITY_INSERT [TABLE_NAME] OFF
GO
I guess I need to wrap this in a loop. Sorry my T-SQL is not that strong, hence the request for help.
Also it would be helpful to omit all tables with TABLE_NAME starting with aspnet_ and use only TABLE_TYPE = "BASE TABLE"
Any help hugely appreciated.
Unless somebody else knows a trick that I don't, you're probably stuck using dynamic SQL and iterating through a list of table names using either a cursor or a temporary table. The cursor approach would look something like this:
declare #TableName nvarchar(257);
declare #sql nvarchar(max);
declare TableCursor cursor read_only for
select
TABLE_SCHEMA + '.' + TABLE_NAME
from
INFORMATION_SCHEMA.TABLES
where
TABLE_NAME not like 'aspnet\_%' escape '\' and
TABLE_TYPE = 'BASE TABLE';
open TableCursor;
fetch next from TableCursor into #TableName;
while ##fetch_status = 0
begin
set #sql = 'select top 1 * from ' + #TableName;
exec sp_executesql #sql;
fetch next from TableCursor into #TableName;
end
close TableCursor;
deallocate TableCursor;
You can read more about cursors here. Alternatively, you could do it with an in-memory table like this:
declare #Tables table (RowId int identity(1, 1), TableName nvarchar(257));
declare #TableName nvarchar(257);
declare #Index int;
declare #TableCount int;
declare #sql nvarchar(max);
insert into #Tables (TableName)
select
TABLE_SCHEMA + '.' + TABLE_NAME
from
INFORMATION_SCHEMA.TABLES
where
TABLE_NAME not like 'aspnet\_%' escape '\' and
TABLE_TYPE = 'BASE TABLE';
set #TableCount = ##rowcount;
set #Index = 1
while #Index <= #TableCount
begin
select #TableName = TableName from #Tables where RowId = #Index;
set #sql = 'select top 1 * from ' + #TableName;
exec sp_executesql #sql;
set #Index = #Index + 1;
end
In the interest of brevity, my examples use a much simpler SQL statement than yours—I'm just selecting one record from each table—but this ought to be enough to illustrate how you can get this done.

Add columns in multiple databases

I need to add 3 new columns to a table named Requirements in all the databases (of same instance). I searched in net to find sp_MSforeachdb can be used to execute same query on multiple databases, but could not find any example with a alter command.
Thanks in advance
Presuming the tables will all be in the same schema then using sp_msforeachdb
EXEC sp_msforeachdb '
IF DB_ID(''?'') > 4
BEGIN
IF EXISTS(SELECT 1 FROM [?].INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME=''Requirements'' AND TABLE_SCHEMA=''dbo''
AND TABLE_TYPE=''BASE TABLE'')
BEGIN
ALTER TABLE [?].dbo.Requirements
ADD col1 INT, col2 INT, col3 INT
END
END
'
Aaron Bertrand wrote a superior version here that you may want to use.
Another way with dynamic sql
DECLARE #sql VARCHAR(MAX) = CAST((SELECT 'IF EXISTS(SELECT 1 FROM [' + name + '].INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=''Requirements'' AND TABLE_SCHEMA=''dbo'' AND TABLE_TYPE=''BASE TABLE'')' + CHAR(10)
+ ' ALTER TABLE [' + name + '].[dbo].[Requirements] ADD Col1 INT, Col2 INT, Col3 INT' + CHAR(10) + CHAR(10)
FROM master.sys.databases
WHERE database_id > 4
FOR XML PATH('')) AS NVARCHAR(MAX))
PRINT #sql
--EXEC(#sql)
If you have to take into consideration the possibility that the table is not in dbo or a common schema then you can use sp_msforeachdb to retrieve the schema information along the lines of
CREATE TABLE ##tmp (DatabaseName SYSNAME, SchemaName SYSNAME, TableName SYSNAME)
EXEC sp_msforeachdb '
IF DB_ID(''?'') > 4
BEGIN
INSERT INTO ##tmp (DatabaseName, SchemaName, TableName)
SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME
FROM [?].INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = ''Requirements''
AND TABLE_TYPE=''BASE TABLE''
END
'
DECLARE #sql VARCHAR(MAX) = CAST((SELECT 'ALTER TABLE [' + DatabaseName + '].[' + SchemaName + '].[' + TableName + '] ADD Col1 INT, Col2 INT, Col3 INT' + CHAR(10) + CHAR(10)
FROM ##tmp
FOR XML PATH('')) AS NVARCHAR(MAX))
PRINT #sql
--EXEC(#sql)
DROP TABLE ##tmp
From mysql command line:
ALTER TABLE database1.table_name ADD column_name column-name;
ALTER TABLE database2.table_name ADD column_name column-name;
..
The following code would generate commands for each database:
select 'ALTER TABLE [' + d.name + '].[dbo].[table_name] ADD column_name column-name;' as cmd
from sys.databases d
where d.name NOT IN ( 'tempdb', 'msdb', 'master','model');
You could also write a cursor to loop over these and execute them, but I would advise looking at what you're executing and making sure you aren't updating the wrong databases.

Resources