SQL SERVER 2005 IF ELSE - sql

I am running following query.
SELECT T1.C1, T2.C2...,
IF( T1.C1<>T2.C1,"Changed","1") AS NewColumn
From T1 INNER JOIN T2
Where condition..
I am getting syntax error for IF statement.
Motive is to compare columns from two different tables, if not equal save as "Changed" in NewColumn of third table.. This is a Insert INTO query.
T-> Table
C->Column

You have to use CASE WHEN in this context.
SELECT T1.C1,
T2.C2...,
CASE WHEN T1.C1<>T2.C1 THEN 'Changed' ELSE '1' END AS NewColumn
FROM T1
INNER JOIN T2
WHERE condition

SELECT T1.C1, T2.C2...,
CASE WHEN T1.C1<>T2.C1 THEN 'Changed' ELSE '1' END AS NewColumn
From T1 INNER JOIN T2 ON ...
Where ...

Others have already mentioned that you should use CASE WHEN ELSE END. The difference between the two is that IF changes the flow of execution of your code - you can conditionally execute code depending on the result of your IF statement. CASE doesn't change the execution flow - it simply lets you check a value, and then get a different result depending on the result.

When you want to use condition checks inside the statement, you should use CASE WHEN
MSDN
But if you have multiline statements, the you can use IF ELSE clause

Related

how to handle invalid index id error in netezza while using array_split?

SELECT T1.AC_NO FROM TALE1 T1
INNER JOIN TABLE2 T2
ON T1.AC_NO=
CASE
WHEN T2.COMMON_KEY LIKE '%~%' AND T2.COMMON_KEY IS NOT NULL
THEN GET_VALUE_VARCHAR(ARRAY_SPLIT(T2.COMMON_KEY,'~'),2)
ELSE T2.COMMON_KEY
END
DATA IN TABLE1:
AC_NO
1
2
3
4
DATA IN TABLE2
COMMON_KEY
A~1~EF
B~2~CD
3
4
ABOVE QUERY THROWS AN ERROR OF :
ERROR [HY000] ERROR: 0 : Invalid Index Id
Scott is onto something here- just make sure it never fails. My suggestion would be to concatenate an extra '~' at the end of the string inside the case:
SELECT T1.AC_NO
FROM TABLE 1T1
INNER JOIN TABLE2 T2
ON T1.AC_NO=
CASE
WHEN T2.COMMON_KEY LIKE '%~%' AND T2.COMMON_KEY IS NOT NULL
THEN GET_VALUE_VARCHAR(ARRAY_SPLIT(T2.COMMON_KEY||'~','~'),2))
ELSE T2.COMMON_KEY
END;
A matter of preference, but I find it more readable :)
For whatever reason Netezza evaluates the THEN expression of a case involving UDFs (which the array fucntions from the SQL Extention Toolkit you are using happen to be) whether the WHERE expression is true or not.
What is happening here is that because of this behavior, it tries to pull the 2nd element from arrays with only one element, giving you the "Invalid Index ID" error when it tries to execute GET_VALUE_VARCHAR(...,2) on the arrays with only 1 value (e.g. 3 and 4), even though you'd think the CASE should never need to test that.
A workaround can be made by making the THEN expression not fail, regardless.
SELECT T1.AC_NO
FROM TABLE 1T1
INNER JOIN TABLE2 T2
ON T1.AC_NO=
CASE
WHEN T2.COMMON_KEY LIKE '%~%' AND T2.COMMON_KEY IS NOT NULL
THEN GET_VALUE_VARCHAR(ARRAY_SPLIT(T2.COMMON_KEY,'~'),min(array_count(ARRAY_SPLIT(T2.COMMON_KEY,'~')),2))
ELSE T2.COMMON_KEY
END;

SELECT-CASE-IN-SELECT error: [SQL0115] Comparison operator IN not valid. In query db2

i have a problem in a db2 query
I tried run this query
SELECT t.* ,
CASE WHEN column in (SELECT data FROM otherTable WHERE conditions...)
then 5
else 0
end as 'My new data'
FROM table t
WHERE conditions....
But get error
[Error Code: -115, SQL State: 42601] [SQL0115] Comparison operator IN not valid.
When i change the sub-query to where statement like this
SELECT t.*
FROM table t
WHERE column in (SELECT data FROM otherTable WHERE conditions...)
Works fine
Why not work in the case statement? It is a limitation of db2?
And could make an equivalent behavior?
One way to do this is to left join to the table and check if it is not null.
In most cases this will be the fastest way because SQL servers are optimized to perform joins very quickly (but will depend on a number of factors including data model, indexes, data size, etc).
Like this:
SELECT t.* ,
CASE WHEN othertable.data is not null
then 5
else 0
end as 'My new data'
FROM table t
left join otherTable ON otherTable.column = data
WHERE conditions....
Try with using exists condition as below (put the column value in the where clause of subquery) :
SELECT t.* ,
CASE WHEN exists (SELECT data FROM otherTable WHERE conditions... and column=val)
then 5
else 0
end as 'My new data'
FROM table t
WHERE conditions....

CASE WHEN after THEN or Select value from other table

I need to do this:
SELECT
COLUMN1,
COLUMN2,
CASE SOMETHING WHEN 0 THEN 'SOMETHING'
ELSE
CASE SOMETHING1 WHEN 'SOMETHING2' THEN (Here I need my value from other table)
ELSE
...
ELSE
...
END
END
AS SOMETHINGSPECIAL
...
...
...
Entire select is horribly complicated sorry.
In the place after THEN in () I need to take out specific value from other table.
I have tried almost everything there is from joins, to put there SELECT WHERE or CASE WHEN statement it always end up with some error.
Keyword missing etc.
Also maybe problem is inside () there is long concatenate:
''
I need to put that specific value from other table into that concatenate.
It either doesn't want to allow me to use other CASE WHEN after that THEN or I'm doing something wrong.
EDIT (sorry cant post entire query dont wanna have problems in work):
SELECT
A.SOMETHING
CASE WHEN A.LIST_ID IN ('something','something') THEN ' (MY VALUE FROM OTHER TABLE HERE) '
END
AS SOMETHINGSPECIAL
FROM SOMETABLE
...
(MY VALUE FROM OTHER TABLE HERE) I tried to put there Select statement condition, Case statement to take out that one value from other table but it just gives me error.
You can use a correlated subquery:
(CASE SOMETHING
WHEN 0 THEN 'SOMETHING'
ELSE (CASE SOMETHING1
WHEN 'SOMETHING2' THEN (select value from othertable ot where ot.col = x.col)
ELSE . . .
Do note that you don't need nested cases. You could write this as:
(CASE WHEN SOMETHING = 0 THEN 'SOMETHING'
WHEN SOMETHING1 = 'SOMETHING2' THEN (select value from othertable ot where ot.col = x.col)
ELSE . . .
END)
You could try joining the table that the other values should come from, that's if there is a link between those tables, so these is what you should do
SELECT
T1.COLUMN1,
T2.COLUMN1,
T.The-column-you-want-from-table2
iNNER JOIN TABLE2 T2 ON T2.cOUMN1 = T1.COLUMN1
So there is no need for a case statement, because from what I can gather from your question, you want a representation value of a value from another table
Here is another more specific example,
Select
Transaction.OrderId
Transaction.OrderDate
Order.StatusDescription
From Transaction
Inner Join Order on Order.OrderID = Transaction.OrderID
In the above example, the StatusDescription is what need from the "other" table, this can be anything from paid,out-of-stock or whatever status. This status in your first table is represented by a number like 1 for paid, 2 for out of stock etc.....
Hope this helps

SQL Sybase Query Strange Behaviour

I've got 2 tables with exactly the same structure in the same Sybase database but they're separate tables.
This query works on one of the 2:
select * from table1 where
QUOTA_FIELD >
(SELECT
count(ACCOUNT) FROM
table1 As t1
where SECTOR = t1.SECTOR
AND
STATUS = 'QUOTA'
)
But for the second table I have to change it to this:
select * from table2 as tref where
QUOTA_FIELD >
(SELECT
count(ACCOUNT) FROM
table2 As t2
where tref.SECTOR = t2.SECTOR
AND
STATUS = 'QUOTA'
)
There's a restriction on where this will execute which means it needs to work like in the first query.
Does anyone have any ideas as to why the first might work as expected and the second wouldn't?
Since I am not yet allowed to comment, here as an answer to the question "does anyone...?":
No. I couldn't find anyone :)
This first query cannot work correctly, since it compares a column with itself (as long as the column names are all normal ASCII characters and not some similar looking UNICODE ones). Please give a proof that the result of this query is in every case the same as of query 2.
Also, the second query would normally be done like that: where SECTOR = tref.SECTOR...
You might be looking for something like this in query #1 :
select * from table1 t2 where
QUOTA_FIELD >
(SELECT
count(ACCOUNT) FROM
table1 As t1
where t2.SECTOR = t1.SECTOR
AND
t1.STATUS = 'QUOTA'
)
This explicitly specifies that the table in subquery is joining with the table in outer query ( co-related subquery ).
If this works, use the same idea in query #2

SQL: Get a random entry iff condition is false

Using Firebird:
I want to select a random entry in the table if the first SQL query returns 0 rows. Is there anyway to combine these two queries?
SELECT * FROM table WHERE cond=1;
SELECT FIRST 1 * FROM table ORDER BY rand();
Im using ExecuteNativeQuery on the java-side which takes basic SQL statements. Sadly, If-Else statements don't work. And if i could make a single query to the database instead of two, that would make my code appear faster.
try this: Not sure but think it will work...
Select FIRST 1 t1.*
FROM table t1
left Join Table t2
On t2.pk = t1.pk
And t2.cond=1
ORDER BY Case When t2.Cond = 1
Then 0 Else rand() End
if(exists(select 1 from table where cond=1))
SELECT * FROM table WHERE cond=1;
else
SELECT FIRST 1 * FROM table ORDER BY rand();
something like this, though I forgot whether the then keyword is needed in if statements in FirebirdSQL databases.