简体   繁体   English

如果SQL Server存储过程中的其他语句

[英]If Else Statement in SQL Server stored procedure

In SQL Server, on .NET you can add together a SQL statement and therefor use either 'or' or 'and'. 在SQL Server的.NET上,您可以添加一条SQL语句,因此可以使用“或”或“与”。

I am stuck how to do this in a SQL Server stored procedure. 我被困在SQL Server存储过程中如何执行此操作。

Question: 题:

  1. What is it called what you add together SQL statements? 您将SQL语句加在一起又叫什么? I have a feeling it starts with a 'c' concocations?? 我感觉它始于“ c”概念?

  2. I believe I am close with the below code to having a 'variable' SQL? 我相信我接近下面的代码来使用“可变” SQL?

Code: 码:

BEGIN
    SELECT * 
    FROM TblEmployee
    WHERE 
       FirstName LIKE  '%' + LTRIM(RTRIM((@sFirstName))) + '%'   
       or
       Surname LIKE '%' + LTRIM(RTRIM((@sSurname ))) + '%'   
       and
       IF (LTRIM(RTRIM((@sOfficeBase))) = 'xyz1234') 
       and OfficeBase = LTRIM(RTRIM((@sOfficeBase)))
       ELSE
       or
       OfficeBase= LTRIM(RTRIM((@sOfficeBase)))
END  

There are simular queries such as If else in stored procedure sql server 在存储过程sql server中有类似的查询,例如If else

But I have a feeling I searching for the 'wrong' question. 但是我有一种寻找“错误”问题的感觉。 Thanks in advance 提前致谢

The where clause allows you to embed conditional logic - you don't need if/then/else, which is just as well, because afaik, that's not supported by any SQL dialect in a where clause. where子句允许您嵌入条件逻辑-不需要if / then / else,这也是一样,因为afaik在where子句中不受任何SQL方言的支持。

BEGIN
    SELECT * 
    FROM TblEmployee
    WHERE 
       FirstName LIKE  '%' + LTRIM(RTRIM((@sFirstName))) + '%'   
       or
       Surname LIKE '%' + LTRIM(RTRIM((@sSurname ))) + '%'   
       and
       (OfficeBase = 'xyz1234' 
       or
       OfficeBase= LTRIM(RTRIM((@sOfficeBase)))
END  

I am pretty sure you have some missing parenthesis in your original query. 我很确定您的原始查询中缺少括号。 Not sure why you are adding LTRIM and RTRIM to your parameters. 不知道为什么要在参数中添加LTRIM和RTRIM。 Taking a shot in the dark I suspect you could boil down your query to this. 我在黑暗中开枪,我怀疑您可以简化对此的查询。

SELECT * --This should be the column names actually needed, * is not good for production code
FROM TblEmployee 
WHERE 
(
    FirstName LIKE  '%' + @sFirstName + '%'   
    or
    Surname LIKE '%' + @sSurname + '%'   
)
and OfficeBase in ('xyz1234', @sOfficeBase)

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

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