简体   繁体   English

在SQL Server函数中返回可为空的类型

[英]Return nullable type in SQL Server function

Is it possible to create a SQL Server function which returns a nullable string? 是否可以创建返回可为空的字符串的SQL Server函数?

I would like to create a function which returns DBNull if the value is 0 or an empty string: 我想创建一个函数,如果值是0或空字符串,则返回DBNull:

Create FUNCTION [dbo].[SetDBNullNvarChar] (@input nvarchar(1000))
RETURNS (needs to be nullable)
AS
BEGIN
    if (@input = '' OR @input = 0) 
    BEGIN
    RETURN null
    END
return @input
END

Any data type in SQL can be set to null unless a not null restriction is put on it. SQL中的任何数据类型都可以设置为null,除非对其施加非null限制。 Therefore you should be able to use whatever return type best suits your needs... 因此,您应该能够使用最适合您需要的任何返回类型...

In your calling code, you'd have to check to see if the returned value is equal to DBNull.Value and have your code act accordingly. 在调用代码中,您必须检查返回的值是否等于DBNull.Value并使代码相应地起作用。

This does return NULL for me: 这确实为我返回了NULL

Create FUNCTION [dbo].[SetDBNullNvarChar] (@input nvarchar(1000))
RETURNS NVARCHAR
AS
BEGIN
    if (@input = '' OR @input = 0) 
    BEGIN
    RETURN null
    END
return @input
END

SELECT  [dbo].[SetDBNullNvarChar](0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM