I have a database with one table, Queries
. This table has two columns, name
and Query
. In column named Query
I'm recording some SQL statements.
I'm trying to execute these statements after selecting them from the table.
This is my code, but output is incorrect, only the statements listed, without execution:
DECLARE @STR_QUERY NVARCHAR(max);
SET @STR_QUERY = 'SELECT Query FROM [AccHelper].[dbo].[Queries]'
EXECUTE SP_EXECUTESQL @STR_QUERY
Try below:
DECLARE @STR_QUERY NVARCHAR(max);
SET @STR_QUERY = (SELECT Query FROM [AccHelper].[dbo].[Queries])
EXECUTE SP_EXECUTESQL @STR_QUERY
This should help you go through all scripts in that table. With what you are doing, only one script will be run so if the table has 100 Scripts, only one will be executed. Hope this helps
DECLARE @Queries TABLE (ID INT IDENTITY(1,1),SQLScript VARCHAR(MAX))
DECLARE @STR_QUERY VARCHAR(MAX);
DECLARE @StartLoop INT
DECLARE @EndLoop INT
INSERT INTO @Queries
SELECT Query
FROM [AccHelper].[dbo].[Queries]
SELECT @EndLoop = MAX(ID), @StartLoop = MIN(ID)
FROM @Queries
WHILE @StartLoop < = @EndLoop
BEGIN
SELECT @STR_QUERY = SQLScript
FROM @Queries
WHERE ID = @StartLoop
EXEC (@STR_QUERY)
SET @StartLoop = @StartLoop + 1
END
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