T-SQL: How to use parameters in dynamic SQL?

后端 未结 4 1757
春和景丽
春和景丽 2020-11-30 11:33

I have the following dynamic query which is working fine without the WHERE clause, which is expecting UNIQUEIDENTIFIER.

When I pass it in,

相关标签:
4条回答
  • 2020-11-30 11:42

    You must pass in the parameters to sp_executesql. See MSDN for details.

    ...
     WHERE 
        CreatedBy = @p
    ...
    
    EXECUTE sp_executesql @sql, N'@p UNIQUEIDENTIFIER', @p = @p_CreatedBY
    
    0 讨论(0)
  • 2020-11-30 11:52
    DECLARE @ParmDefinition NVARCHAR(500)
    SET @ParmDefinition = '@p_CreatedBy UNIQUEIDENTIFIER'
    
    EXEC sp_executesql @sql, @ParmDefinition, @p_CreatedBy = @p_CreatedBy
    
    0 讨论(0)
  • 2020-11-30 11:54

    I'm not sure if your variable is getting populated in string format or binary, but you may need to quote the uniqueidentifier in your where clause. If you just select the uniqueidentifier field, does it come back as string or binary?

    0 讨论(0)
  • 2020-11-30 11:58

    Multiple parameter syntax. Maybe this will save someone an extra Google Search:

    exec sp_executesql 
        @qry, 
        N'@value1 int, @value2 int, @currentValue int', 
        @value1 = @value1, @value2 = @value2, @currentValue = @currentValue
    
    0 讨论(0)
提交回复
热议问题