Reputation:
I'm currently experiencing with JSON and SQL, I'm trying to write a dynamic sql command but sql server always says "Must declare the scalar variable "@AgencesP"" and I don't know what i'm doing wrong because if I try a SELECT * FROM @AgencesP
i have my data.
DECLARE @AgencesP TABLE (Agence INT, Groupe INT)
DECLARE @P VARCHAR(MAX)
DECLARE @SQLC VARCHAR(MAX)
SET @P = N'{ "Agences":[ 1, 6 ],"Groupes":[ 40, 45 ] }' --Agences
INSERT INTO @AgencesP (Agence, Groupe)
SELECT *
FROM OpenJSON(@P,'$.Agences')
WITH(Agence INT '$')
LEFT JOIN OpenJSON(@P,'$.Groupes')
WITH(Groupe INT '$') ON 1=1
SET @SQLC = 'SELECT TOP 20 * '+
'FROM GRH_T_Salarie '+
'INNER JOIN @AgencesP ON GRH_T_Salarie.IdAgenceExploitation ='[email protected]
Upvotes: 0
Views: 297
Reputation: 29943
You can simplify the statement:
DECLARE @P VARCHAR(MAX)
SET @P = N'{ "Agences":[ 1, 6 ],"Groupes":[ 40, 45 ] }' --Agences
SELECT TOP 20 *
FROM GRH_T_Salarie
INNER JOIN (
SELECT Agence, Groupe
FROM OPENJSON(@P,'$.Agences') WITH (Agence INT '$')
OUTER APPLY OPENJSON(@P,'$.Groupes') WITH (Groupe INT '$')
) agnt ON GRH_T_Salarie.IdAgenceExploitation = agnt.Agence
Of course, if you are ... trying to write a dynamic sql command ... (although you do not need a dynamic statement), passing a table as a parameter needs a table type declaration:
CREATE TYPE AgencesPType AS TABLE (Agence INT, Groupe INT)
DECLARE @AgencesP AgencesPType
DECLARE @P VARCHAR(MAX)
DECLARE @SQLC NVARCHAR(MAX)
SET @P = N'{ "Agences":[ 1, 6 ],"Groupes":[ 40, 45 ] }' --Agences
INSERT INTO @AgencesP (Agence, Groupe)
SELECT *
FROM OpenJSON(@P,'$.Agences')
WITH(Agence INT '$')
LEFT JOIN OpenJSON(@P,'$.Groupes')
WITH(Groupe INT '$') ON 1=1
SET @SQLC =
N'SELECT TOP 20 * '+
N'FROM GRH_T_Salarie g '+
N'INNER JOIN @AgencesP a ON g.IdAgenceExploitation = a.Agence'
EXEC sp_executesql @SQLC, N'@AgencesP AgencesPType READONLY', @AgencesP
Upvotes: 1
Reputation:
Edit : I got it working by removing the dynamic SQL command :) Code if someone need it :
DECLARE @AgencesP TABLE (Agence INT, Groupe INT)
DECLARE @P VARCHAR(MAX)
DECLARE @SQLC VARCHAR(255)
SET @P = N'{ "Agences":[ 1, 6 ],"Groupes":[ 40, 45 ] }' --Agences
INSERT INTO @AgencesP (Agence, Groupe)
SELECT *
FROM OpenJSON(@P,'$.Agences')
WITH(Agence INT '$')
INNER JOIN OpenJSON(@P,'$.Groupes')
WITH(Groupe INT '$') ON 1=1
SELECT TOP 20 *
FROM GRH_T_Salarie
INNER JOIN @AgencesP agnt ON GRH_T_Salarie.IdAgenceExploitation = agnt.Agence
Upvotes: 0
Reputation: 14389
Try with an alias, like:
SET @SQLC = 'SELECT TOP 20 * '+
'FROM GRH_T_Salarie '+
'INNER JOIN @AgencesP agnt ON GRH_T_Salarie.IdAgenceExploitation =agnt.Agence'
Upvotes: 0