在SQL Server存储过程中使用IF语句

时间:2021-08-24 02:07:44

I'm using the IF statement like this:

我用的是IF语句

ALTER proc spGetUserLevelCode 
( 
    @strLoginID VARCHAR(20) = '', @outdata int  output
) AS

if(select level_code 
    from org_person with(nolock) 
    where person_code = @strLoginID) = 'CA40'

as you can see, I extend CA50, CA60 like this adding behind 'CA40' or 'CA50' or 'CA60' but there is an error

正如你所看到的,我将CA50, CA60扩展到CA40或CA50或CA60后面,但是有一个错误。

How can I use additional condition in IF condition?

在IF条件下如何使用附加条件?

3 个解决方案

#1


4  

Use

使用

IN ('CA40','CA50','CA60' )

Or

 LIKE 'CA[4-6]0'

Not = 'CA40' or 'CA50' or 'CA60'

不等于'CA40'或'CA50'或'CA60'

#2


1  

I think I'd prefer to use an exists in this case

我想在这种情况下我更喜欢用存在

ALTER proc spGetUserLevelCode 
( 
    @strLoginID VARCHAR(20) = '', @outdata int  output
) AS

if exists(select *
    from org_person with(nolock) 
    where person_code = @strLoginID
    AND level_code IN ('CA40','CA50','CA60') )
BEGIN
    --DO SOMETHING
END

#3


0  

You can use either way as below:

你可以使用以下两种方式:

IF EXISTS(SELECT 1
   FROM org_person WITH(NOLOCK) 
   WHERE person_code = @strLoginID
        AND level_code IN ('CA40','CA50','CA60') )
BEGIN
  -- Other statement goes here
END

OR

IF EXISTS(SELECT 1
   FROM org_person WITH(NOLOCK) 
   WHERE person_code = @strLoginID
        AND level_code LIKE 'CA[4-6]0' )
BEGIN
  -- Other statement goes here
END

#1


4  

Use

使用

IN ('CA40','CA50','CA60' )

Or

 LIKE 'CA[4-6]0'

Not = 'CA40' or 'CA50' or 'CA60'

不等于'CA40'或'CA50'或'CA60'

#2


1  

I think I'd prefer to use an exists in this case

我想在这种情况下我更喜欢用存在

ALTER proc spGetUserLevelCode 
( 
    @strLoginID VARCHAR(20) = '', @outdata int  output
) AS

if exists(select *
    from org_person with(nolock) 
    where person_code = @strLoginID
    AND level_code IN ('CA40','CA50','CA60') )
BEGIN
    --DO SOMETHING
END

#3


0  

You can use either way as below:

你可以使用以下两种方式:

IF EXISTS(SELECT 1
   FROM org_person WITH(NOLOCK) 
   WHERE person_code = @strLoginID
        AND level_code IN ('CA40','CA50','CA60') )
BEGIN
  -- Other statement goes here
END

OR

IF EXISTS(SELECT 1
   FROM org_person WITH(NOLOCK) 
   WHERE person_code = @strLoginID
        AND level_code LIKE 'CA[4-6]0' )
BEGIN
  -- Other statement goes here
END