Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Using the IF statement on a table

Author  Topic 

Xercister
Starting Member

6 Posts

Posted - 2013-03-28 : 17:03:18
Is it possible to use an IF statement to check a value in a row of a table?

My whole idea is to have a query that checks for a certain value and if that value exists then do say an update statement. If it doesn't find that value then it will need to do something else.


IF row = xxxvaluexx
THEN do whatever
ELSE
do whatever

Is that possible?

jimf
Master Smack Fu Yak Hacker

2875 Posts

Posted - 2013-03-28 : 17:13:33
IF EXISTS (select * from yourTable where somefield = 'somevalue')

Do whatever

ELSE
do something else


Jim
Jim

Everyday I learn something that somebody else already knew
Go to Top of Page

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-03-28 : 17:14:42
You would use CASE expressions rather than IF statements. IF construct in SQL is for control flow; while you can use IF in sort of a roundabout way for doing what you are attempting to do, CASE expressions are probably better suited. See examples below:
update tablename set
yourColumnA = case when YourColumnB = 'X' then 'Updated' end;


update tablename set
yourColumnA = case when YourColumnB = 'X' then 'Updated' ELSE 'Not Updated' end;
Go to Top of Page

Xercister
Starting Member

6 Posts

Posted - 2013-03-28 : 20:05:46
Ah, thanks for both replies guys. I'll look into both!
Go to Top of Page
   

- Advertisement -