没有数据插入时,SQL Server OUTPUT子句甚至不返回NULL?

时间:2015-01-28 11:15:10

标签: sql-server

当没有插入数据时,我希望@docId为0.我似乎无法使这个工作。我尝试使用MAX和/或COALESCE,但没有成功。我错过了什么? (实际插入数据时工作正常)。

DECLARE @NewDoc TABLE(DocId int)

INSERT INTO someTable
OUTPUT inserted.DocID INTO @NewDoc
SELECT some Fields
    FROM dbo.Documents d
    WHERE some conditions
PRINT 'Docs created: ' + cast( @@rowcount as char(10));

--save newly created docId into variable
select @DocId = COALESCE(DocId,0) from @NewDoc

--do more stuff using @DocId

--return @docId at end of storedProc
SELECT @docId Result

1 个答案:

答案 0 :(得分:0)

由于当@NewDoc @DocID剩余null中没有数据时,您需要将其更改为

select @DocId = DocId from @NewDoc

if (@docID is null)
  set @docID = 0