Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - execute query from table cells

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
like image 797
Димитър Грудев Avatar asked Mar 30 '17 14:03

Димитър Грудев


2 Answers

Try below:

DECLARE @STR_QUERY NVARCHAR(max);
SET @STR_QUERY = (SELECT Query FROM [AccHelper].[dbo].[Queries])

EXECUTE SP_EXECUTESQL @STR_QUERY
like image 28
Pawel Czapski Avatar answered Sep 21 '22 14:09

Pawel Czapski


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
like image 170
Gouri Shankar Aechoor Avatar answered Sep 24 '22 14:09

Gouri Shankar Aechoor