I have a table that stores dynamically constructed T SQL queries in one of the table's column. My requirement is that I need to execute the query formed (in my case, some insert statements) and I 'dont want to use a while loop' to traverse the whole rows and then executing the statements from a variable. Also I dont want to use a cursor. The table has around 5 million of dynamically formed SQL insert statements. I had earlier tried this thing using a while loop but it was taking days to complete, and so I dropped it.
To run a dynamic SQL statement, run the stored procedure sp_executesql as shown below : EXEC sp_executesql N'SELECT statement'; Use prefix N with the sp_executesql to use dynamic SQL as a Unicode string.
Executing dynamic SQL using sp_executesql sp_executesql is an extended stored procedure that can be used to execute dynamic SQL statements in SQL Server. we need to pass the SQL statement and definition of the parameters used in the SQL statement and finally set the values to the parameters used in the query.
With dynamic SQL, you can directly execute most types of SQL statement, including data definition and data control statements. You can build statements in which you do not know table names, WHERE clauses, and other information in advance.
Had to look up what `lakh' was :)
As other comments mentioned this is not most optimal approach to DML, please consider refactoring. As it is you can combine your dynamic SQL in batches, e.g.:
DECLARE @sSQL nvarchar(max)
SET @sSQL = 'BEGIN TRAN; '
SELECT @sSQL = @sSQL + COLUMN_WITH_INSERT_STATEMENT + '; '
FROM TABLE
WHERE [limit number of rows]
SET @sSQL = @sSQL + 'COMMIT TRAN '
EXEC(@sSQL)
This way you can combine controlled number of INSERT statements into a single transaction. You can control number of inserts by means of WHERE statement (e.g. WHERE ID BETWEEN 1 and 100
to execute 100 INSERTs at a time) You can loop thru this condition (yes loop, but it it will not be looping thru individual rows, but thru conditions instead e.g.1 - 100, 101 - 200, 201 - 300 etc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With