开发者

if statement in my sql server 2008 select or my update query?

开发者 https://www.devze.com 2023-02-28 06:20 出处:网络
Can I have an IF state开发者_开发知识库ment in my select query or in an update query? I want to set different values based on some substring values in my DB.you would use a CASE statement

Can I have an IF state开发者_开发知识库ment in my select query or in an update query?

I want to set different values based on some substring values in my DB.


you would use a CASE statement

select case Column when 'a' then 'bla' else 'not bla' end as SomeColumn
from SomeTable

Runnable example

select case xtype 
when 'p' then 'stored procedure' 
when 'd' then 'default'
when 'u' then 'table'
else 'something else' end as SomeType
 from sysobjects


Sure you can

... SET field = CASE WHEN cond THEN val1 ELSE val2 END, ...


Use the CASE expression in order to make such evaluations as part of your SELECT.

Here is an example from MSDN:

SELECT   ProductNumber, Category =
      CASE ProductLine
         WHEN 'R' THEN 'Road'
         WHEN 'M' THEN 'Mountain'
         WHEN 'T' THEN 'Touring'
         WHEN 'S' THEN 'Other sale items'
         ELSE 'Not for sale'
      END,
   Name
FROM Production.Product


Yes, you can use case

0

精彩评论

暂无评论...
验证码 换一张
取 消