Pat*_*ick 2 sql-server string null casting
我有一些使用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
Run Code Online (Sandbox Code Playgroud)
这完全有效,直到ContentName为NULL然后它崩溃,我忘了你需要将值转换为字符串,然后才能将它们添加到nvarchar列.那么在我将它插入Errors表之前如何转换@ContentName?
你不需要强制转换 - 使用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, ''))
Run Code Online (Sandbox Code Playgroud)
作为旁注,SQL Server提供了可用于将数据从一种类型转换为另一种类型的方法cast和convert方法.你在这里不需要它,但很高兴知道.