0

I have a query like :

DECLARE @jsonVariable NVARCHAR(MAX)
SET @jsonVariable =  
N'{ "id" : "11","info": { "fname": "John", "surname": "Smith" }, "age": "25" }'  

INSERT INTO Employees
SELECT *  
FROM OPENJSON(@jsonVariable)  
  WITH (id int,fname nvarchar(50) '$.info.fname') 

How to use a dynamic TableName after INSERT INTO instade of Employees?

I have tried with sp_executesql:

DECLARE @jsonVariable NVARCHAR(MAX)
DECLARE @TABLENAME NVARCHAR(MAX) = 'Students'
DECLARE @SQL NVARCHAR(100)

SET @jsonVariable =  N'{ "id" : "11","info": { "fname": "John", "surname": "Smith" }, "age": 25 }'   

SET @SQL = 'INSERT INTO '+ @TABLENAME +' SELECT *  FROM 
OPENJSON(@jsonVariable); WITH (id int ,age nvarchar(50))'
EXEC sp_executesql @SQL

But getting the error : Must declare the scalar variable "@jsonVariable". Is there any way to do it?

2
  • You've basically got it. Change @jsonVariable to '+@jsonVariable+' to pass the variable into your dynamic SQL string Commented Mar 29, 2018 at 14:31
  • You are defining the variable outside of the executesql so it does not know what it is. Commented Mar 29, 2018 at 14:31

1 Answer 1

3

Please use like this.

CREATE TABLE Em
(
     Id INT
    ,fName VARCHAR(10)
)
GO

DECLARE @jsonVariable NVARCHAR(MAX)
DECLARE @TableName VARCHAR(10) = 'Em'
SET @jsonVariable =  
    N'{ "id" : "11","info": { "fname": "John", "surname": "Smith" }, "age": 25 }'  

DECLARE @SQL AS VARCHAR(MAX) = '

INSERT INTO ' + @TableName + '
SELECT *  
FROM OPENJSON(' + '''' + @jsonVariable + '''' + ')  
  WITH (id int,fname nvarchar(50) ''$.info.fname'') '

EXEC(@SQL)
SELECT * FROM Em

OUTPUT

Id          fName
----------- ----------
11          John

(1 rows affected)
Sign up to request clarification or add additional context in comments.

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.