如何在OPENJSON查询中使用动态table_name?

时间:2018-03-29 14:23:33

标签: sql json sql-server

我有一个类似的查询:

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') 

如何在INSERT INTO instade of Employees之后使用动态TableName?

我尝试过使用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

但是得到错误:必须声明标量变量" @ jsonVariable"。 有没有办法做到这一点?

1 个答案:

答案 0 :(得分:2)

请像这样使用。

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

<强>输出

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

(1 rows affected)