SQL - execute query from table cells
I have a database with one table Queries
. This table has two columns, name
and Query
. In the column named Query
I am writing some SQL statements.
I am trying to execute these statements after selecting them from a table.
This is my code, but the output is wrong, only the listed statements without execution:
DECLARE @STR_QUERY NVARCHAR(max);
SET @STR_QUERY = 'SELECT Query FROM [AccHelper].[dbo].[Queries]'
EXECUTE SP_EXECUTESQL @STR_QUERY
+5
source to share
2 answers
This will guide you through all the scenarios in this table. With what you are doing, only one script will run, so if the table has 100 scripts, only one will be executed. Hope it 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
+3
source to share