tsql - 在用户定义的函数中 try catch ?

标签 tsql user-defined-functions

我正在尝试编写一个 UDF 来将一个 guid 或与该 guid 关联的项目代码的字符串转换为 guid:

CREATE FUNCTION fn_user_GetProjectID 
(
    @Project nvarchar(50)
)
RETURNS uniqueidentifier
AS
BEGIN

    declare @ProjectID uniqueidentifier

    BEGIN TRY
        set @ProjectID = cast(@Project as uniqueidentifier)
    END TRY
    BEGIN CATCH
        set @ProjectID = null
    END CATCH

    if(@ProjectID is null)
    BEGIN
        select  @ProjectID = ProjectID from Project where projectcode = @Project
    END

    return @ProjectID

END

如果上面的代码嵌入在我的存储过程中,这很好用,但我想用它制作一个函数,以便我遵循 DRY。

当我尝试创建函数时,出现如下错误:
Msg 443, Level 16, State 14, Procedure fn_user_GetProjectID, Line 16
Invalid use of side-effecting or time-dependent operator in 'BEGIN TRY' within a function.

有谁知道我如何解决这个错误?

编辑:我知道我不能在函数中使用Try-Catch,我想这是一个简化的问题,有没有一种方法可以进行转换,如果转换失败,它只会返回NULL而不是错误?

最佳答案

来自 MSDN :

A column or local variable of uniqueidentifier data type can be initialized to a value in the following ways:

By using the NEWID function.

By converting from a string constant in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, in which each x is a hexadecimal digit in the range 0-9 or a-f.

For example, 6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid uniqueidentifier value.



您可以使用模式匹配来验证字符串。请注意,这不适用于减小 GUID 大小的特定编码:
declare @Project nvarchar(50) 

declare @ProjectID uniqueidentifier 
declare @HexPattern nvarchar(268) 

set @HexPattern =  
    '[A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9]' +  
    '[A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9]' +  
    '[A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9]' +  
    '[A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9][A-F0-9]' 

/* Take into account GUID can have curly-brackets or be missing dashes */
/* Note: this will not work for GUIDs that have been specially encoded */
set @Project = '{' + CAST(NEWID() AS VARCHAR(36)) + '}'

select @Project

set @Project = REPLACE(REPLACE(REPLACE(@Project,'{',''),'}',''),'-','')

/* Cast as uniqueid if pattern matches, otherwise return null */ 
if @Project LIKE @HexPattern 
  select @ProjectID = CAST(
         SUBSTRING(@Project,1,8) + '-' + 
         SUBSTRING(@Project,9,4) + '-' + 
         SUBSTRING(@Project,13,4) + '-' + 
         SUBSTRING(@Project,17,4) + '-' + 
         SUBSTRING(@Project,21,LEN(@Project)-20)
         AS uniqueidentifier) 

select @ProjectID

关于tsql - 在用户定义的函数中 try catch ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3206221/

相关文章:

mysql - 在用户定义的函数(mysql)中格式化日期

pandas - Pyspark Pandas_UDF 错误,参数无效,而不是字符串或列

sql-server - 动态设置 ORDER BY,无需字符串连接

sql - T-SQL 输出插入子句 - 访问不在插入/删除表中的数据

sql - Sql Server 中的版本号排序

sql - 外部查询先于内部查询运行

c - 使用 libjpeg 读取图像像素数据的 3 维数组的内存分配

sql - 插入上一行

apache-spark - 计算pyspark数据框中的地理距离

MySQL 用户定义函数,内部嵌套查询