November 16, 2016 at 5:01 pm
Hi guys,
Can someone please help me to convert below tsql script to sqlcmd?
I need to connect to a server and instance and delete all tables in a database where the name of the table exists as a column value in the table dbo.tblSum and run it on sqlcmd.
DECLARE @DELETE_TEMPLATE NVARCHAR(MAX) = N'
USE {{@DATABASENAME}}
BEGIN TRY
TRUNCATE TABLE dbo.{{@TABLENAME}};
END TRY
BEGIN CATCH
DELETE FROM dbo.{{@TABLENAME}};
END CATCH
';
DECLARE @DELETE_SQL NVARCHAR(MAX) =
(
SELECT
REPLACE(REPLACE(@DELETE_TEMPLATE
,N'{{@TABLENAME}}'
,QUOTENAME(ATAB.TableName)
)
,N'{{@DATABASENAME}}'
,QUOTENAME(ATAB.DatabaseName)
)
FROM dbo.tblSum ATAB
FOR XML PATH(''),TYPE
).value('(./text())[1]','NVARCHAR(MAX)');
SELECT @DELETE_SQL;
EXEC (@DELETE_SQL);
Thank you so much in advance!
DBA newbie
November 16, 2016 at 5:05 pm
* I need to delete all rows of all tables.
November 16, 2016 at 7:30 pm
whitesql (11/16/2016)
* I need to delete all rows of all tables.
It would be easier on you and the system to create the scripts for all the tables, drop the tables, and rebuild them from the scripts. Just trying to delete rows is going to be slow, bloat the log file, be slow, not always work because of dependencies, be slow, fire all delete triggers, and be slow.
Also...
1. Why do you need to do this through SQLCMD and
2. Why do you need to do this at all?
--Jeff Moden
Change is inevitable... Change for the better is not.
November 17, 2016 at 9:37 am
I agree with most of what Jeff said, but I would TRUNCATE the tables rather than scripting, dropping, and recreating them.
Drew
J. Drew Allen
Business Intelligence Analyst
Philadelphia, PA
November 17, 2016 at 11:14 am
drew.allen (11/17/2016)
I agree with most of what Jeff said, but I would TRUNCATE the tables rather than scripting, dropping, and recreating them.Drew
Don't forget... If they have FKs on them, TRUNCATE is out of the question unless you drop or disable the FKs.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 5 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy