【问题标题】:MS SQL 2008 cast null to stringMS SQL 2008 将 null 转换为字符串
【发布时间】:2009-09-20 11:26:41
【问题描述】:

我有一些使用 TRY/CATCH 语句的存储过程,所以我执行主程序,如果它产生任何错误,我会捕获它们。现在我的问题出在 catch 语句中,我有这段代码:

            BEGIN TRY
        INSERT INTO ContentTypes (ContentName, ContentPath) VALUES (@ContentName, @ContentPath)

        SET @QResult = 0
    END TRY
    BEGIN CATCH         

        SET @QResult = 1
        INSERT INTO Errors (ErrorNumber, ErrorLine, ErrorProcedure, ErrorSeverity, ErrorState, ErrorParameters)
        VALUES (ERROR_NUMBER(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_SEVERITY(), ERROR_STATE(), 'ContentName:' + @ContentName + ',ContentPath:' + @ContentPath)
        RETURN
    END CATCH

这在 ContentName 为 NULL 然后崩溃之前完美运行,我忘记了您需要将值转换为字符串,然后才能将它们添加到 nvarchar 列。那么我该如何转换 @ContentName 在我将其插入错误表之前?

【问题讨论】:

    标签: sql-server string casting null


    【解决方案1】:

    您不需要强制转换 - 使用 coalesce 函数:

    返回其参数中的第一个非空表达式。

    你会这样使用它:

    insert into Errors (ErrorNumber, ErrorLine, 
        ErrorProcedure, ErrorSeverity, ErrorState, ErrorParameters)
    values (ERROR_NUMBER(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_SEVERITY(), 
        ERROR_STATE(), 'ContentName:' 
        + coalesce(@ContentName, '')
        + ',ContentPath:' + coalesce(@ContentPath, ''))
    

    附带说明一下,SQL Server 提供了cast and convert methods,可用于将数据从一种类型转换为另一种类型。您在这里不需要它,但很高兴知道。

    【讨论】:

      【解决方案2】:

      作为对@Andrew Hare's answer 的补充,我会稍微不同地格式化您的字符串:

      insert into Errors (ErrorNumber, ErrorLine, 
          ErrorProcedure, ErrorSeverity, ErrorState, ErrorParameters)
      values (ERROR_NUMBER(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_SEVERITY(), 
          ERROR_STATE()
          ,'ContentName:' + coalesce('"'+@ContentName+'"', 'null') 
          + ',ContentPath:' + coalesce('"'+@ContentPath+'"', 'null')
      

      这样做,您可以判断变量是空字符串还是空值。变量的值在双引号之间,所以 "" 是一个空字符串," " 是一个空格,而 null 是空值。这三个值经常会出现错误。

      【讨论】:

        猜你喜欢
        • 2023-04-11
        • 2012-04-12
        • 1970-01-01
        • 2021-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-01
        • 1970-01-01
        相关资源
        最近更新 更多