简体   繁体   中英

Error Must declare scalar variable in sql server

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 ='+@AgencesP.Agence

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    

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'

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

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