user3532047
user3532047

Reputation: 11

Need help converting If/then to CASE in SQL

I'm having some trouble grasping the use of CASE statements (used to using If/Then). I would like to convert this to CASE format:

If DATEPART(Month,Datetime) = 04
       Then UPDATE DB1
       SET column1 = (SELECT Value FROM DB2)

So if the month of the current datetime matches 4 (April), then update column1 of DB1 with the values in the Value column of DB2. How would this look using CASE?

Upvotes: 0

Views: 105

Answers (3)

qxg
qxg

Reputation: 7036

I don't think there is equal CASE statement for your query.

Check CASE express in MSDN

Evaluates a list of conditions and returns one of multiple possible result expressions.

Your query is a conditional UPDATE operation which doesn't return anything. Could you clarify your intention here?

Upvotes: 0

MatBailie
MatBailie

Reputation: 86706

IF ((SELECT DATEPART(MONTH, GetDate())) = 04)
  UPDATE
    db1
  SET
    column1 = db2.value
  FROM
    db2
  WHERE
    db1.key = db2.key

The DATEPART() is embedded in a SELECT which is itself enclosed in ().

The WHERE clause is needed to specify which rows in db2 are used to update which rows in db1.

In T-SQL there is no THEN. See here for details.

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269553

I am unclear what case has to do with this. The case statement would normally be used in a select to execute conditional statements. Your update seems more like:

update db1
    set column1 = db2.value
    from db1 join
         db2
         on db1.foo = db2.bar
    where DATEPART(Month, db1.Datetime) = 4;

But it is a bit hard to divine from your question what you are really trying to do.

EDIT: (in response to comment)

For todays date, the where clause should be:

where datepart(month, getdate()) = 4

Instead of the where, you can use if (datepart(month, getdate()) = 4) . . ..

The join (or subquery) is needed because the question refers to two tables.

Upvotes: 2

Related Questions