Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute A Dynamic SQL statement Stored in a Column of a table

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.

like image 901
Dibin Avatar asked Aug 26 '13 13:08

Dibin


People also ask

How do you execute dynamic SQL queries?

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.

How Dynamic SQL can be executed?

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.

Which statements can be executed by Dynamic SQL?

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.


1 Answers

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).

like image 127
Yuriy Galanter Avatar answered Sep 30 '22 17:09

Yuriy Galanter