动态SQL执行问题

时间:2018-08-23 14:13:26

标签: sql sql-server sql-server-2012

执行以下Quotes时出现Quotes错误。我用双引号替换了硬代码值

 declare @query nvarchar(MAX)
    set @query = 'SELECT PID AS EID,
    ''637'' + p.SSN + SPACE(9- LEN(RTRIM(LTRIM(ISNULL(p.SSN,'')))))
    + ''98''
    + CONVERT(VARCHAR(6), GETDATE(), 12)
    + SPACE(9)
    + ''A1''
    + @Str1
    + @Str2
    + ISNULL(LEFT(UPPER(@Str1),30),'') + SPACE(30- LEN(RTRIM(LTRIM(ISNULL(LEFT(@Str1,30),'''')))))
    + ISNULL(LEFT(UPPER(@Str2),30),'') + SPACE(30- LEN(RTRIM(LTRIM(ISNULL(LEFT(@Str2,30),'''')))))
    + SPACE(1)
    + SPACE(8) AS Data, GETDATE() AS CreatedOn
    INTO #Temp
    FROM dbo.PERSON p'

    exec sp_executesql @query;



INSERT INTO  dbo.RKS_TransactionData
SELECT * FROM #Temp

1 个答案:

答案 0 :(得分:1)

isnull()的问题是您需要在''''中使用isnull()(已经完成但部分完成了):

 declare @query nvarchar(MAX)

 set @query = 'SELECT PID AS EID,
    ''637'' + p.SSN + SPACE(9- LEN(RTRIM(LTRIM(ISNULL(p.SSN,'''')))))
    + ''98''
    + CONVERT(VARCHAR(6), GETDATE(), 12)
    + SPACE(9)
    + ''A1''
    + @Str1
    + @Str2
    + ISNULL(LEFT(UPPER(@Str1),30),'''') + SPACE(30- LEN(RTRIM(LTRIM(ISNULL(LEFT(@Str1,30),'''')))))
    + ISNULL(LEFT(UPPER(@Str2),30),'''') + SPACE(30- LEN(RTRIM(LTRIM(ISNULL(LEFT(@Str2,30),'''')))))
    + SPACE(1)
    + SPACE(8) AS Data, GETDATE() AS CreatedOn
    INTO #Temp
    FROM dbo.PERSON p'

    print @query -- see how query looks or try to compile query

    exec sp_executesql @query;