MS SQL 2008 将 null 转换为字符串
我有一些使用 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 在我将其插入错误表之前?
I got a few stored procedures that uses a TRY/CATCH statement, so i execute the main program and if it generates any errors i catch them. Now my problem is in the catch statement, i have this piece of code:
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
This works perfectly until ContentName is NULL then it crashes, i forgot that you need to cast the values to string before you can add them to a nvarchar column. So how do i convert
@ContentName before i insert it into the Errors table?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要强制转换 - 使用
合并
函数:您可以像这样使用它:
作为旁注,SQL Server 提供
cast
和convert
方法,可用于将数据从一种类型转换为另一种类型。您在这里不需要它,但了解它是件好事。You don't need to cast - use the
coalesce
function:You would use it like this:
As a side note, SQL server offers
cast
andconvert
methods that you can use to convert data from one type to another. You don't need it here but it is good to know.作为 @Andrew Hare 的回答的额外一点,我会稍微不同地格式化你的字符串:
这样做,你可以判断变量是空字符串还是空。变量的值将在双引号之间,因此 "" 是一个空字符串," " 是一个空格,null 将是无效的。这三个值经常会出现错误。
as an extra point to @Andrew Hare's answer, I would format your strings a little differently:
doing it this way, you can tell if the variable was an empty string or was null. The variables will have their value between double quotes, so "" is an empty string, and " " is a single space and null would be null. Bugs crop up quite often with these three values.