SQL - 使用需要String的参数

时间:2018-05-28 01:00:39

标签: sql-server tsql

我在过程中有一个参数,它允许用户包含要使用的JSON文件的文件位置。我的问题是,SQL不允许我使用参数,给我错误:

  

无法批量加载。文件“@JSONFileLocation”不存在。

并且在尝试删除''时,错误:

  

期待STRING或TEXT_LEX。

这是完整的程序:

ALTER PROCEDURE main.mainRun @JSONFileLocation NVARCHAR(MAX)
AS
    BEGIN TRY

DECLARE @Details NVARCHAR(MAX)

SELECT @Details = 
    BulkColumn
    FROM OPENROWSET(BULK @JSONFileLocation ,SINGLE_CLOB) JSON

    INSERT INTO main.jsontable (dateloaded,name,surname,email,age,balance,country,registered)
    (SELECT GETDATE(), [Name],[Surname],[Email],[Age],[Balance],[Country],[Registered]
    FROM OPENJSON(@Details,'$.PersonDetails.Person')        
    WITH(
        [Name] NVARCHAR(50)         '$.first_name',
        [Surname] NVARCHAR(50)      '$.last_name',
        [Email] NVARCHAR(50)        '$.email',
        [Age] NVARCHAR(50)          '$.age',
        [Balance] NVARCHAR(50)      '$.balance',
        [Country] NVARCHAR(50)      '$.country',
        [Registered] NVARCHAR(50)   '$.registered'
        )
    )

    EXEC main.generateStatistics

    END TRY
    BEGIN CATCH  
    SELECT  
        CONCAT('Error Number:',ERROR_NUMBER(),'|Error Message:',ERROR_MESSAGE(),'|Error Procedure:',ERROR_PROCEDURE()) AS 'Error'
    END CATCH;  

1 个答案:

答案 0 :(得分:0)

问题在于您的OPENROWSET查询。您需要使用Dynamic Sql将Path作为参数传递给OPENROWSET。有点像...

ALTER PROCEDURE main.mainRun 
    @JSONFileLocation NVARCHAR(MAX)
AS
BEGIN
    BEGIN TRY

    DECLARE   @Details  NVARCHAR(MAX)
            , @Sql      NVARCHAR(MAX);

    SET @Sql = N' SELECT @Details = BulkColumn
                  FROM OPENROWSET(BULK ''' + @JSONFileLocation + ''',SINGLE_CLOB) JSON;';

    Exec sp_executesql @Sql
                      , N'@Details  NVARCHAR(MAX) OUTPUT'
                      , @Details OUTPUT;

    INSERT INTO main.jsontable
                       (dateloaded,name,surname,email,age,balance,country,registered)
    SELECT GETDATE(), [Name],[Surname],[Email],[Age],[Balance],[Country],[Registered]
    FROM OPENJSON(@Details,'$.PersonDetails.Person')        
    WITH(
        [Name]      NVARCHAR(50)    '$.first_name',
        [Surname]   NVARCHAR(50)    '$.last_name',
        [Email]     NVARCHAR(50)    '$.email',
        [Age]       NVARCHAR(50)    '$.age',
        [Balance]   NVARCHAR(50)    '$.balance',
        [Country]   NVARCHAR(50)    '$.country',
        [Registered] NVARCHAR(50)   '$.registered'
        )

    EXEC main.generateStatistics;

    END TRY
    BEGIN CATCH  
    SELECT  
        CONCAT  ('Error Number:',ERROR_NUMBER()
                ,'|Error Message:',ERROR_MESSAGE()
                ,'|Error Procedure:',ERROR_PROCEDURE()) AS 'Error'
    END CATCH

END