Hi, I'm having trouble creating a dynamic SQL statement to execute. I have to truncate tables with '_history' in the name, and of a certain size or more. For that, I've created a temp table called #ConvertedSizes and I insert table names in it. Next, I have to execute 'Truncate [table];' statement. I've managed to get that statement as output but struggling to create a dynamic SQL out of it **within the same script** and execute it. I've tried different number of single quotes, but haven't had success. Here's the script: SELECT 'TRUNCATE TABLE '+TABLE_NAME+ ';' FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%_history%' and TABLE_NAME in (SELECT Name from #ConvertedSizes) 1. I'll appreciate some help in generating the 'Truncate [table];' script above - possibly have a @sqlScript of varchar(500) and assign the statement to it. 2. A brief primer/rule-of-thumb on how to approach such problems using single quotes, so as to reduce trial-and-error. Thanks.
Something like this might be a good starting point: DECLARE @SQL varchar(MAX) = '' SELECT @SQL = @SQL + 'TRUNCATE TABLE ' + QUOTENAME(TABLE_NAME) + ';' -- corrected as per comment FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%_history%' AND TABLE_NAME IN (SELECT Name from #ConvertedSizes); SELECT @SQL; --EXEC (@SQL); Comment out the last line when you're sure that the statement held in @SQL is being generated properly Code not tested for anything, including actually being right, let alone working in SQL 2012. Seriously, you're going to run untested code that you don't understand on your database?