1

As example I will create a temp table:

CREATE TABLE #TembTable  
(
      Command VARCHAR(max)  
) 

Insert the values toin the table

INSERT INTO #TembTable (Command)
VALUES ('SELECT @@VERSION AS Version_Name ;'),
       ('SELECT @@LANGUAGE AS Current_Language;'),
       ('SELECT @@LANGID AS Language_ID ;'),
       ('SELECT @@SERVERNAME AS Server_Name;'),
       ('SELECT @@SERVICENAME AS Service_Name;')

If I select all values

SELECT * FROM #TembTable

Result will show:

SELECT @@VERSION AS Version_Name ;
SELECT @@LANGUAGE AS Current_Language;
SELECT @@LANGID AS Language_ID ;
SELECT @@SERVERNAME AS Server_Name;
SELECT @@SERVICENAME AS Service_Name;

What I am trying to do is to execute each command automatically.

Thanks.

3
  • To run SQL stored in a table, you need a loop to process multiple rows one at a time, and then sp_executesql to execute the dynamic SQL. Commented Aug 23, 2020 at 20:12
  • You may also want to have a temp table that has an ORDER - not a random one as you ahve. i.e. add an ID field so you can execute them ordered by ID. Otherwise you may or may not get them in the same order when retrieving. Commented Aug 24, 2020 at 10:33
  • Why not simply create a view? create view ... as select @@version as version_name, @@language as current_language, ... Commented Aug 24, 2020 at 10:45

2 Answers 2

2

You must declare a variable

DECLARE @Statements NVARCHAR(MAX);

Fill this variable with the commands from #Temptable

SET @Statements = ( SELECT STRING_AGG (CONVERT(NVARCHAR(MAX),Command), NCHAR(13)) 
                    FROM   #TembTable)
;

and execute it:

EXECUTE (@Statements)
;
Sign up to request clarification or add additional context in comments.

Comments

0

A select query is a database object that shows information in Datasheet view. A query does not store data, it displays data that is stored in tables. A query can show data from one or more tables, from other queries, or from a combination of the two. (https://support.microsoft.com/en-us/office/create-a-simple-select-query-de8b1c8d-14e9-4b25-8e22-70888d54de59#:~:text=A%20select%20query%20is%20a,a%20combination%20of%20the%20two)

If your intention is to get the values for the statements then you can incorporate a stored procedure to do the above.

CREATE PROCEDURE Getdetails
AS
BEGIN
    SELECT @@VERSION AS Version_Name ;
    SELECT @@LANGUAGE AS Current_Language;
    SELECT @@LANGID AS Language_ID ;
    SELECT @@SERVERNAME AS Server_Name;
    SELECT @@SERVICENAME AS Service_Name;
END;

to get o/p: The below will retrieve all details that you needed

exec Getdetails

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.