-2

我正在尝试执行插入语句,但我正在检查之前是否已插入数据,如果是,则不会在表中插入该行。完成后,我想返回实际插入的行数。任何人都可以帮忙添加一个计数器吗?我正在使用SQL Server 2012.

我的查询如下:

        If NOT EXISTS (Select Id from @List where Id = cast(@IG_Id as int))
BEGIN  
       SET @Sql = 
          'INSERT INTO '+@List+' (Id,Id,LCode,CellNumber,WorkNumber,HomeNumber)
           VALUES ('''+@CId+''','''+@LId+''','''+@LCode+''','''+@MobileNumber+''','''+@BusinessNumber+''','''+ @HomeNumber+''')'
           print @Sql END
4

1 回答 1

0

试试这个

If NOT EXISTS (Select Id from @List where Id = cast(@IG_Id as int))
BEGIN 
    INSERT INTO @List (Id,Id,LCode,CellNumber,WorkNumber,HomeNumber)
    VALUES (@CId, @LId, @LCode, @MobileNumber, @BusinessNumber, @HomeNumber)
END 

SELECT @@ROWCOUNT as NumberOfInsertedRows  

实际上,由于您只有一个要插入的值列表, @@ROWCOUNT因此只能是 0 或 1


编辑:显示如何从另一个表插入

INSERT INTO @List (Id,Id,LCode,CellNumber,WorkNumber,HomeNumber)
select Id,Id,LCode,CellNumber,WorkNumber,HomeNumber
from [MyDataSetTable]
where CAST([MyDataSetTable].IG_Id as int) not in (select Id from @List)

SELECT @@ROWCOUNT as NumberOfInsertedRows
于 2013-09-16T08:01:20.663 回答