sql函数检查表的任一列中是否存在任何值

时间:2014-03-25 14:45:43

标签: sql sql-server-2008 function

我是新手,并且在使用这个sql函数时遇到了一些困难。 我试图在sql中创建一个函数,但它不起作用,它接受@A int和@B int的参数 返回" bit"的数据类型。试图检查表C和D中是否存在@A int或@B int。如果存在 返回值1,否则为0

这是我的代码

CREATE FUNCTION fn_exist(
@A int, @B int
)
RETURNS bit
as
begin

Declare @year int
    select @year as [year]
    case [YEAR] when @A in (C or D)
    or @B in (C and D)
    then 1 else 0
    from dbo.mytable
    return @year 

end

2 个答案:

答案 0 :(得分:2)

试试这个:

Declare @value as bit

select @value =
case
    when exists(
      select 1
      from dbo.mytable
      where (@A = C OR @A = D) OR (@B = C OR @B = D)
    )
    then 1 else 0
end

return @value 

答案 1 :(得分:0)

看看你的代码示例我认为你想要这样的东西:

DECLARE @value AS BIT
IF EXISTS(
   SELECT NULL
   FROM dbo.mytable
   WHERE (@A = C OR @A = D) OR (@B = C OR @B = D)
) 
   SET @value = CAST(1 As bit)
ELSE 
   SET @value = CAST(0 As bit)

RETURN @value