简体   繁体   中英

Injecting variable in nested EXEC in stored procedure

New to SQL and i'm working on a separate.network so i can't share snippets (sorry) so bare with me please.

I have a stored procedure that has a table injected, based on this table i want it to run a specific part of the script (if else else if...)

Before I start adding the ELSEs i want to ensure the IF first works.
It goes something like this within my alter procedure:

ALTER PROCEDURE dbo.TestProc (@table VARCHAR(50))
AS
BEGIN
DECLARE @sql AS VARCHAR(MAX)
SET @sql = 
   N'IF EXISTS (SELECT PersonID FROM ' + @table + ')
      BEGIN 
      EXEC SP_EXECUTIONSQL N''''
         INSERT INTO dbo.TEST(PerID, Name, Age) SELECT T.PerID, T.Name, T.Age 
         FROM ''' + @table + ''' T  
         END' 
-- Before the apostrophe on the END i'd add the else, but again, i want to test this first.   
EXEC (SQL); 
END

The issue i'm having when i run EXEC TestProc 'Employees' is Incorrect syntax near 'Employees' - the nested injected @table in the second FROM.

For background, I am nesting the EXEC SP_EXECUTIONSQL Because i was having the same issue as this person .
Also, i simplified my table significantly for various reasons, so alternative solutions may not be feasible.

I tried just using IF ELSE statements normally, but i discovered from a previously posted question that everything is compiled before the IF statement, and so the injected table overrides the IF statement and injects it into IF and every ELSE i throw in there.

What i was expecting was for the script to stop once the conditions of the IF ELSE were met.

You have quotes that your shouldn't and missing quotes that you need. You also have a typo so_executionsql should be sp_executesql .

I reformatted your code to make it easier.

Try this...

SET @sql = N'
  IF EXISTS (SELECT PersonID FROM ' + QUOTENAME(@TABLE) + ')
  BEGIN 
    EXEC SP_EXECUTESQL N''
      INSERT INTO dbo.TEST(PerID, Name, Age)
        SELECT T.PerID, T.Name, T.Age 
        FROM ' + QUOTENAME(@TABLE) + ' T
    '';
  END
'

In fact, you don't even need the nested calls to exec...

SET @sql = N'
  IF EXISTS (SELECT PersonID FROM ' + QUOTENAME(@TABLE) + ')
  BEGIN
    INSERT INTO dbo.TEST(PerID, Name, Age)
      SELECT T.PerID, T.Name, T.Age 
      FROM ' + QUOTENAME(@TABLE) + ' T;
  END
'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM