I do not want to use cursors for performance reasons. Input Parameters for stored procedure: arg1, arg2,arg3 & arg4 For example: Table A > A1 Column and A2 Column, Table B > B1 Column (A.A1 <=>B.B1) foreign n primary key relation and B2 Column.
I want to update A.A2 value based on the following if condition,
if(arg1 == B.B2 && arg2 == B.B2)
{
Update A set A.A2 = 1 where A.A1 = arg4
}
else{
if(arg1 == 1 && arg3 == B.B2){
Update A set A.A2 = 0 where A.A1 = arg4
}
}
this is simple for one record but the Table A has 1000's records 开发者_StackOverflowthat match A.A1 = arg4 so i have to apply the above logic or case for all records and want to avoid using cursors...how do i do it?
Try the below query.
UPDATE tmp
SET tmp.A2 =
(CASE WHEN (tmp1.B2 == arg1 && tmp1.B2 == arg2) THEN 1 WHEN (arg1 == 1 && tmp1.B2 == arg3) THEN 0 ELSE tmp.A2)
FROM
A tmp
INNER JOIN
B tmp1
ON tmp.A1 = tmp1.B1
WHERE
tmp.A1 = arg4
Hope this Helps!!
In general, non-specific SQL-92 you could do this:
UPDATE A
SET A.A2 = CASE WHEN B.B2 IN (@Arg1,@Arg2) THEN 1
WHEN @arg1 = 1 AND B.B2 = @arg3 THEN 0 END
FROM A
JOIN B ON A.A1=B.B1
WHERE A.A1 = @arg4
You may need an ELSE
before END
if you don't want any values falling through (without the ELSE
it would set A.A2 to NULL
).
精彩评论