动态SQL错误 - 将值设置为参数

时间:2015-12-08 13:22:53

标签: sql sql-server sql-server-2005 dynamic-sql

我有一个动态的SQL。

magic

执行此附加错误时。 作为文本的错误也附加了这个。 有什么想法吗?

declare @CustomerId int
set @CustomerId = 1
declare @SDate datetime 
set @SDate = '2015/12/07'
declare @ItemId int
set @ItemId = 2

declare @QtyS nvarchar(max)
declare @QtyOut decimal(18,3)

set @QtyS = 'SELECT isnull(sum(d.Qty),0)
FROM InvoiceDetail AS d INNER JOIN
InvoiceHeader AS h ON d.InvoiceNo = h.InvoiceNo
where
h.CustomerId = '''+@CustomerId+''' and
d.itemmasterid = '''+@ItemId+''' and
h.Deleted = 0 and
h.invoicedate = '''+@SDate+''''

exec sp_executesql @QtyS, N'@Qty decimal(18,3) out', @QtyOut out
select @QtyOut

enter image description here

1 个答案:

答案 0 :(得分:0)

DECLARE
      @CustomerId INT = 1
    , @ItemId INT = 2
    , @SDate DATETIME = '2015/12/07'
    , @QtyS NVARCHAR(MAX)
    , @QtyOut DECIMAL(18,3)

SET @QtyS = '
SELECT @QtyOut = SUM(d.Qty)
FROM dbo.InvoiceDetail d
JOIN dbo.InvoiceHeader h ON d.InvoiceNo = h.InvoiceNo
WHERE h.CustomerId = @CustomerId
    AND d.itemmasterid = @ItemId
    AND h.Deleted = 0
    AND h.invoicedate = @SDate'

EXEC sp_executesql @QtyS,
                   N'@CustomerId INT, @ItemId INT, @SDate DATETIME, @QtyOut decimal(18,3) out',
                   @CustomerId = @CustomerId, @ItemId = @ItemId, @SDate = @SDate, @QtyOut = @QtyOut OUT

SELECT @QtyOut
  

必须声明标量变量“@QtyS”

DECLARE
      @CustomerId INT = 1
    , @ItemId INT = 2
    , @SDate DATETIME = '2015/12/07'
    , @QtyS NVARCHAR(MAX)
    , @QtyOut DECIMAL(18,3)

SET @QtyS = '
SELECT @QtyOut = 1
SELECT @CustomerId, @ItemId, @SDate'

EXEC sp_executesql @QtyS,
                   N'@CustomerId INT, @ItemId INT, @SDate DATETIME, @QtyOut decimal(18,3) out',
                   @CustomerId = @CustomerId, @ItemId = @ItemId, @SDate = @SDate, @QtyOut = @QtyOut OUT

SELECT @QtyOut

2005:

DECLARE
      @CustomerId INT
    , @ItemId INT
    , @SDate DATETIME
    , @QtyS NVARCHAR(MAX)
    , @QtyOut DECIMAL(18,3)

SELECT
      @CustomerId = 1
    , @ItemId = 2
    , @SDate = '2015/12/07'

SET @QtyS = '
SELECT @QtyOut = SUM(d.Qty)
FROM dbo.InvoiceDetail d
JOIN dbo.InvoiceHeader h ON d.InvoiceNo = h.InvoiceNo
WHERE h.CustomerId = @CustomerId
    AND d.itemmasterid = @ItemId
    AND h.Deleted = 0
    AND h.invoicedate = @SDate'

EXEC sp_executesql @QtyS,
                   N'@CustomerId INT, @ItemId INT, @SDate DATETIME, @QtyOut DECIMAL(18,3) OUT',
                   @CustomerId = @CustomerId, @ItemId = @ItemId, @SDate = @SDate, @QtyOut = @QtyOut OUT

SELECT @QtyOut