Truncate selected tables in SQL Server - sql-server

How to truncate selective tables in SQL Server 2008,
I have a list of tables which may be excluded during truncate process.
Can anybody guide me?

You can simply run TRUNCATE TABLE yourTableName. If you have a list you can run the following:
CREATE TABLE #truncateTables(name nvarchar(255))
INSERT INTO #truncateTables(name) VALUES(N'dbo.yourTable1'),(N'dbo.yourTable2')
DECLARE cur CURSOR FOR
SELECT name FROM #truncateTables
OPEN cur
DECLARE #sql nvarchar(max), #tabname nvarchar(255)
FETCH NEXT FROM cur INTO #tabname
WHILE ##FETCH_STATUS = 0 BEGIN
SET #sql = N'TRUNCATE TABLE '+#tabname
BEGIN TRY EXEC(#sql)
END TRY
BEGIN CATCH -- if a foreign key constraint exists
SET #sql = N'DELETE FROM '+#tabname
EXEC(#sql)
END CATCH
FETCH NEXT FROM cur INTO #tabname
END
CLOSE cur
DEALLOCATE cur
DROP TABLE #truncateTables

Related

Execute queries stored in columns of a SQL Server table

I have a table with 2 columns QueryName and Query. I am trying the execute the queries stored in the Query column of the table.
I want to display anything that has more than record count of zero, we need to print to output with queryname and count. I am using the following cursor, I was able to display rowcount but anyone please suggest me how to display the QueryName:
DECLARE #Sql NVARCHAR(MAX);
DECLARE Cur CURSOR LOCAL FAST_FORWARD FOR
(SELECT Query
FROM VWLetterTYB )
OPEN Cur
FETCH NEXT FROM Cur INTO #Sql
WHILE (##FETCH_STATUS = 0)
BEGIN
--Exec sp_executesql #Sql
EXEC ('SELECT COUNT(*) AS Rowcounts FROM (' + #sql + ') AS t HAVING COUNT(*) > 0 ')
FETCH NEXT FROM Cur INTO #Sql
END
CLOSE Cur
DEALLOCATE Cur;
DECLARE #Sql NVARCHAR(MAX);
DECLARE Cur CURSOR LOCAL FAST_FORWARD FOR
(SELECT Query
FROM VWLetterTYB )
OPEN Cur
FETCH NEXT FROM Cur INTO #Sql
WHILE (##FETCH_STATUS = 0)
BEGIN
--Exec sp_executesql #Sql
EXEC ('SELECT [sql] = ''' + #Sql + ''', COUNT(*) AS Rowcounts FROM (' + #sql + ') AS t HAVING COUNT(*) > 0 ')
FETCH NEXT FROM Cur INTO #Sql
END
CLOSE Cur
DEALLOCATE Cur;
If I understand you correctly, you have two fields in the table but you only managed to get one using the cursor. In that case, the solution is easy, you can fetch more than one value with a cursor (each one to a different variable), then just put that value in the dynamic SELECT:
DECLARE #Sql NVARCHAR(MAX), #QueryName NVARCHAR(MAX);
DECLARE Cur CURSOR LOCAL FAST_FORWARD FOR
(SELECT Query, QueryName
FROM VWLetterTYB )
OPEN Cur
-- variables are filled in the order used in the SELECT (first column to first variable,
-- second column to second variable, etc.)
FETCH NEXT FROM Cur INTO #Sql, #QueryName
WHILE (##FETCH_STATUS = 0)
BEGIN
-- when using single quotes inside a string you have to double it
EXEC ('SELECT '''+ #QueryName+''' AS QueryName, COUNT(*) AS Rowcounts FROM (' + #sql + ') AS t HAVING COUNT(*) > 0 ')
FETCH NEXT FROM Cur INTO #Sql, #QueryName
END
CLOSE Cur
DEALLOCATE Cur;
I don't have an answer, but a further refinement of the question. The examples here are using the stored SQL as a standalone command. Can a snippet of SQL stored in a table's column be used as an item in a SELECT list?
I have a situation where I have a table of code/name lookup pairs. Most codes lead to a single name. But something logic needs to be applied to determine the name. I would like to have this seamless in my master SQL statement. I have to apply this logic from the same lookup table in many scripts. I don't want to have to embed complex logic in each script or maintain a convoluted stored procedure.

Stored procedure - Only return if rows > 0

I have this stored procedure which executes a lot of SQL queries and returns the results. How do i go about returning only the results from the queries that returns rows?
BEGIN
DECLARE #Query varchar(4000)
DECLARE cur CURSOR FOR SELECT SQLSyntax FROM tblChecks
OPEN cur
FETCH NEXT FROM cur INTO #Query
WHILE ##FETCH_STATUS = 0 BEGIN
EXEC (#Query)
FETCH NEXT FROM cur INTO #Query
END
CLOSE cur
DEALLOCATE cur
END
Please help me...
To avoid returning empty result sets, you have to conditionally run each query. For instance:
declare #query varchar(4000)
declare cur cursor local for
select 'if exists (' + SQLSyntax + ') ' + SQLSyntax from tblChecks
open cur
fetch next from cur into #query
while ##fetch_status = 0
begin
exec(#query)
fetch next from cur into #query
end
close cur
deallocate cur
Or, if every result set is identical, you could create a temp table first, and then insert all values into the temp table, and then do a single select statement at the end from the temp table:
create #temp (field1 type null, field2 type null, field3 type null)
declare #query varchar(4000)
declare cur cursor local for
select 'insert into #temp ' + SQLSyntax from tblChecks
open cur
fetch next from cur into #query
while ##fetch_status = 0
begin
exec(#query)
fetch next from cur into #query
end
close cur
deallocate cur
select * from #temp
drop table #temp
If possible, the 2nd option is better, because it will only run each query one time. The 1st option will run each query twice (that returns data), once to test if there are any results and once to return the data. This is not efficient! Hopefully all queries return the same fields in the results and you can use the 2nd option.
You can also execute and evaluate the results using the If exists strategy.
IF EXISTS(exec(#query))
BEGIN
exec(#query)
END

Multi-tables joining in Cursor

I got a table of words to be searched in the database and the table
Parameter
id Name Word
----------------------------------
1 word search c&a
2 word search Beton
3 word search Freiman
4 Anything Null
beside that i have the Procedure SearchAllTable, which is the searching Procedure and for searching the words in the database.
DECLARE #id int
DECLARE #name varchar(100)
DECLARE #word varchar(100)
DECLARE cur CURSOR FOR SELECT Id, word FROM #Parameter WHERE Name = 'word search'
OPEN cur
FETCH NEXT FROM cur INTO #id,#word
WHILE ##FETCH_STATUS = 0 BEGIN
EXEC SearchAllTables #word
FETCH NEXT FROM cur INTO #id, #word
END
CLOSE cur
DEALLOCATE cur
the problem that I got the result in multipule tables and I want them all to be listed in one table without any suppuration.
Insert your results into temporary table, created before cursor cycle
UPDATE
try this UNION the results of multiple stored procedures
Collect your result into a temp table or table variable and get it in a single select outside the cursor. Please try the bellow.
DECLARE #id int
DECLARE #name varchar(100)
DECLARE #word varchar(100)
--Create Result table wrt your SP output
DECLARE #Result TABLE (NAME VARCHAR(16), DATEVAL DATETIME)
DECLARE cur CURSOR FOR SELECT Id, word FROM #Parameter WHERE Name = 'word search'
OPEN cur
FETCH NEXT FROM cur INTO #id,#word
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #Result
EXEC SearchAllTables #word
FETCH NEXT FROM cur INTO #id, #word
END
CLOSE cur
DEALLOCATE cur
--Selecting result as a single unit
SELECT * FROM #Result

how to call procedure in procedure in sql server

i have one procedure name Randomoutlet and i want to call that procedure via other procedure as code below
ALTER procedure [dbo].[MainSchedule]
as
begin
DECLARE #sup table (supervisorId int)
INSERT INTO #sup SELECT DISTINCT SupervisorId FROM CallPlan .dbo .CallPlanSchedule WHERE MONTH (scheduledate)= MONTH (GETDATE ()) and YEAR (ScheduleDate )= YEAR(GETDATE())
DECLARE CUR CURSOR FORWARD_ONLY FOR SELECT * FROM #sup
DECLARE #suptem int
OPEN CUR
FETCH NEXT FROM CUR INTO #suptem
WHILE ##FETCH_STATUS =0
BEGIN
EXEC [dbo].[randomOutlet] #suptem
FETCH NEXT FROM CUR INTO #suptem
END
CLOSE CUR
DEALLOCATE CUR
end
when i save MainSchedule it's show message "The module 'MainSchedule' depends on the missing object 'dbo.randomOutlet'. The module will still be created; however, it cannot run successfully until the object exists.
"
and when i run this procedure it's appear error "Msg 2812, Level 16, State 62, Procedure MainSchedule, Line 15
Could not find stored procedure 'dbo.randomOutlet'."
please help me solve this problem thank in advance
I tried the following and got everything running fine.
CREATE procedure CALL_PROC --'abc'
#var varchar(100)
as
begin
declare #sup table (item int)
insert into #sup select 1 union select 2
DECLARE CUR CURSOR FORWARD_ONLY FOR SELECT * FROM #sup
DECLARE #var1 int
OPEN CUR
FETCH NEXT FROM CUR INTO #var1
WHILE ##FETCH_STATUS =0
BEGIN
EXEC dbo.call_me #var1
FETCH NEXT FROM CUR INTO #var1
END
CLOSE CUR
DEALLOCATE CUR
end
go
CREATE PROCEDURE [dbo].[CALL_ME]
#VAR VARCHAR(100)
AS
if OBJECT_ID('tempdb..#temp') is not null
begin
insert into #temp select #VAR
end
else
select #var value into #temp
select * from #temp
go
Please check if you have created the objects on the same DB or not.

Run operations on all the tables in all the databases

I'm trying to create a SQL Server script that applies some operations to all the tables in all the databases. I need to rename some tables if some conditions are respected, truncate the tables otherwise.
This is my script
EXEC sp_MSforeachdb
#command1 = '
IF not exists(select 1 where ''?'' in (''master'',''model'',''msdb'',''tempdb''))
EXEC [?].dbo.sp_MSforeachtable
#command1 = ''
IF(substring(&, 1, 3)=pv_ and right(&, 5) != _data and right(&, 4) != _BCK)
exec sp_RENAME & , &_BCK''
ELSE IF (right(&, 4) != _BCK)
TRUNCATE TABLE &
#replacechar = ''&'''
I got some errors but I'm new to SQL Server and I have not idea how to fix this script.
Any suggestions?
Many thanks
Here is a solution for start. It won't be quick, but it loops all tables of all databases on the server. Inside in the second cursor you can deceide what to do with the table.
(The query is not optimalized, just a quick solution)
DECLARE #DBName NVARCHAR(50)
DECLARE #TableName NVARCHAR(100)
DECLARE #DynamicSQL NVARCHAR(300)
DECLARE #DBCursor CURSOR
SET #DBCursor = CURSOR FOR
SELECT NAME FROM SYS.DATABASES
WHERE NAME NOT IN ('master','tempdb','model','msdb')
OPEN #DBCursor
FETCH NEXT FROM #DBCursor INTO #DBName
WHILE ##FETCH_STATUS = 0
BEGIN
CREATE TABLE #TempTableDatas
(
name varchar(100),
objectID int
)
SET #DynamicSQL = 'INSERT INTO #TempTableDatas
SELECT name, object_id FROM [' + #DBName + ']' + '.sys.Tables '
EXEC SP_EXECUTESQL #DynamicSQL
DECLARE #TableCursor CURSOR
SET #TableCursor = CURSOR FOR
SELECT name FROM #TempTableDatas
OPEN #TableCursor
FETCH NEXT FROM #TableCursor INTO #TableName
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #TableName, #DBName
FETCH NEXT FROM #TableCursor INTO #TableName
END
CLOSE #TableCursor
DEALLOCATE #TableCursor
DROP TABLE #TempTableDatas
FETCH NEXT FROM #DBCursor INTO #DBName
END
CLOSE #DBCursor
DEALLOCATE #DBCursor

Resources