当参数为null时,sp_executesql不返回任何内容

时间:2016-07-06 15:43:21

标签: sql sql-server stored-procedures triggers

我的程序中有这段代码:

   SET @Sql = 'SELECT @Value = ' + @Column + ' FROM #inserted'

   exec sp_executesql @Sql, N'@Value varchar(MAX) out', @NEW out


   SET @Sql = 'SELECT @Value = ' + @Column + ' FROM #deleted'

   exec sp_executesql @Sql, N'@Value varchar(MAX) out', @OLD out

当列值为null时,变量@OLD没有任何内容,并且在我比较2个变量时出于某种原因:

IF @NEW != @OLD

即使IF为空且@OLD不是@NEW,它也不会进入IF @OLD is null or datalength(@OLD)=0 or @NEW != @OLD 。我试过这个:

@OLD

但仍然没有好结果。当我打印2个变量时,WHILE(@LoopCounter <= @MAX) BEGIN SELECT @Column = COLUMN_NAME, @Type = DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE ORDINAL_POSITION = @LoopCounter and TABLE_NAME = 'Parameters' SET @Sql = 'SELECT @Value = ' + @Column + ' FROM #inserted' exec sp_executesql @Sql, N'@Value varchar(MAX) out', @NEW out SET @Sql = 'SELECT @Value = ' + @Column + ' FROM #deleted' exec sp_executesql @Sql, N'@Value varchar(MAX) out', @OLD out IF @OLD is null or datalength(@OLD)=0 or @NEW != @OLD BEGIN /* some code */ END SET @LoopCounter = @LoopCounter + 1 END 不会打印任何内容(在表中为null的情况下)。

你能帮助我吗?

谢谢:)

修改

这是我为数据库中的某些表构建的触发器,当它们更新时,我可以保存所做的更改。为了方便起见,我通过该表的列名创建了一个循环,并且对于每一列,我都会使用那段代码来解决它。这是我的触发器的一部分:

// store the variable refernce in an array
var sign = [signaturePad1, signaturePad2, signaturePad3, signaturePad4, signaturePad5];
// assign click envent to elements and also cache the elements to get index
var $ele = $('[id^="ClearSign"]').click(function() {
  // get element by index and apply clear
  sign[$ele.index(this)].clear();
});

3 个答案:

答案 0 :(得分:0)

所以检查空状态:

IF @NEW != @OLD
OR @NEW IS NULL AND @OLD IS NOT NULL
OR @OLD IS NULL AND @NEW IS NOT NULL
BEGIN
...

答案 1 :(得分:0)

为什么不主动...如果@Column为空,请不要执行..

WHILE(@LoopCounter <= @MAX)
    BEGIN
       SELECT @Column = COLUMN_NAME, @Type = DATA_TYPE
       FROM INFORMATION_SCHEMA.COLUMNS WHERE ORDINAL_POSITION = @LoopCounter and TABLE_NAME = 'Parameters'

       IF ISNULL(@Column,'')<>''
           BEGIN
           SET @Sql = 'SELECT @Value = ' + @Column + ' FROM #inserted'

           exec sp_executesql @Sql, N'@Value varchar(MAX) out', @NEW out


           SET @Sql = 'SELECT @Value = ' + @Column + ' FROM #deleted'

           exec sp_executesql @Sql, N'@Value varchar(MAX) out', @OLD out

           IF @OLD is null or datalength(@OLD)=0 or @NEW != @OLD
           BEGIN
             /* some code */
           END
       END
       SET @LoopCounter  = @LoopCounter  + 1 
END

答案 2 :(得分:0)

好的,我找到了解决方案。谢谢你的提示。我将代码更改为:

       SET @Sql = 'SELECT @Value = ' + @Column + ' FROM #inserted'

       exec sp_executesql @Sql, N'@Value varchar(MAX) out', @NEW out


       SET @Sql = 'SELECT @Value = ' + @Column + ' FROM #deleted'

       exec sp_executesql @Sql, N'@Value varchar(MAX) out', @OLD out

       IF ISNULL(@NEW,0) != ISNULL(@OLD,0)

ISNULL一切正常。我还必须在我的代码中的其他位置使用此功能,我将string@OLD@NEW值连接起来。

谢谢:)