How to execute two queries based on case condition in sql server - sql

I am trying to execute queries based on condition within single table,here is my query in sql server.
where PATTERN is column name and is set to 0 as default value
I want to display result into only one cell of excel sheet. I linked SQL server and Excel sheet.
IF ([PATTERN] = 1)
BEGIN
SELECT PATTERN,COLOR,SHIFT FROM [DEFECT_RESULTS]
END
ELSE
SELECT MODEL,COLOR FROM [DEFECT_RESULTS]
pattern column is present then still following error is displaying
error: Invalid column name 'PATTERN'.

You need to perform a query in the if condition. SQL doesn't know what table/function you're referring to as it stands.
Something like
if exists (select 1 from DEFECT_RESULTS where PATTERN = 1)
begin
…
Which will do the true side of the if if any row in DEFECT_RESULTS matches. You may need a more specific condition.

declare #pattern int
if (#pattern=1)
begin
SELECT PATTERN,COLOR,SHIFT FROM [DEFECT_RESULTS]
end
else if(#pattern=0)
begin
SELECT MODEL,COLOR FROM [DEFECT_RESULTS]
end

A single query cannot return 2 columns sometimes and 3 columns at other times. Perhaps you just want two queries:
SELECT PATTERN, COLOR, SHIFT
FROM [DEFECT_RESULTS]
WHERE PATTERN = 1;
SELECT MODEL, COLOR
FROM [DEFECT_RESULTS]
WHERE PATTERN = 0;

Related

Snowflake case statement is returning an error instead of the value specified within the ELSE clause

I need to check if one or many fields already exists in a table so I can do a merge into statement using them.
I tried this:
select sat_sector_hkey,
CASE
WHEN EXISTS(select id from hub_sector)
THEN (MERGE INTO ...)
END AS id
from sat_sector;
For testing, I used only one case statement, and replaced merge into with a THEN...ELSE values:
SELECT sat_sector_hkey,
CASE
WHEN EXISTS(select id from hub_sector)
THEN '1'
ELSE ''
END AS id
FROM sat_sector;
When this field does not exists, the query return an error instead of '':
SQL compilation error: error line 3 at position 23 invalid identifier
'ID'
I am using a CASE, because I need to check if a column exists or not, as I don't know if it exists or not due to some technicalities in our data coming from multiple sources.
Try this:
Construct an object with the full row.
Test if the constructed object has data for "ID".
create or replace temp table maybe_id
as
select 1 x, 2 id;
select *,
case
when object_construct(a.*):ID is not null
then '1'
else ''
end as id
from maybe_id a
;
Works for me - it gives 1 when the column id has data, and `` when the column doesn't exist in the table.

Displaying an alternative result when derrived table is empty

I have this sql code where I try to display an alternative value as a result whenever the table is empty or the the single column of the top row when it is not
select top 1 case when count(*)!=0 then derrivedTable.primarykey
else 0 end endCase
from
(
select top 1 m.primarykey
from mytable m
where 0=1
)derrivedTable
The problem is that when I run this, I get the error message "column 'derrivedTable.primarykey' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
But when I put 'derrivedTable.primarykey' in the group by clause, I just get an empty table.
Does anyone hve a solution?
thanks in advance
You can use aggregation:
select coalesce(max(m.primarykey), 0)
from mytable m;
An aggregation query with no group by always returns exactly one row. If the table is empty (or all rows are filtered out), then the aggregation functions -- except for COUNT() -- return NULL -- which can be transformed to a value using COALESCE().
Such a construct makes me worry. If you are using this to set the primary key on an insert, then you should learn about identity columns or sequences. The database will do the work for you.
Can you try this below script-
SELECT
CASE
WHEN COUNT(*) = 1 THEN derrivedTable.primarykey
ELSE 0
END endCase
FROM
(
SELECT TOP 1 m.primarykey
FROM mytable m
WHERE 0 = 1
) derrivedTable
derrivedTable.primarykey;

Naming query ouput columns using a separate query T-sql

Im looking for a way to name columns using the top 1 selection from a separate query.
select
case when t.test=1 then 1 else 0 end as select top 1 name from #names,
case when t.test=2 then 1 else 0 end as select top 1 name from #names2
from table t
In this example I want to name then columns by the top selection from several temporary columns. However this does not work. Does anyone have a suggestion on how to make this work?
Thank you in advance,
Philip
The SQL query engine does not evaluate expressions when it expects a column name or alias (any object identifier is expected to be literal).
You can construct your SELECT as a string where you inject the names from subqueries:
declare #stmt nvarchar(max)
set #stmt='
select
case when t.test=1 then 1 else 0 end as ['+(select top 1 name from #names)+'],
case when t.test=2 then 1 else 0 end as ['+(select top 1 name from #names2)+']
from table t'
exec(#stmt)
Security concern
As the word "inject" already implies, this can be vulnerable to injection attacks. Use with caution, and only if you have control over the contents of the #names and #names2 tables - do not use this approach when those tables can contain user input.

SQL SELECT statement within an IF statement

I have a trigger in SQL Server that needs to check on an update the number of rows with a value between a certain amount and do something accordingly. My current code is something like this:
IF EXISTS(SELECT COUNT(id) as NumberOfRows
FROM database
WHERE id = 3 AND value <= 20 and value > 2
GROUP BY id
HAVING COUNT(id) > 18)
-- if true, do something
From what I can tell, the select statement should find the number of rows with a value between 2 and 20 and if there are more than 18 rows, the EXISTS function should return 1 and the query will execute the code within the IF statement.
However, what is happening is that it is always executing the code within the IF statement regardless of the number of rows with a value between 2 and 20.
Any ideas on why this might be? I can post more complete code if it might help.
The reason is that the Exists function is checking the result of the sub-query for existing - are there any rows or not. And, as you return the COUNT, it'll never be not-existing - COUNT returns 0 if there are no rows presented in database.
Try to store the resulting count in a local variable, like in this question:
Using IF ELSE statement based on Count to execute different Insert statements
DECLARE #retVal int
SELECT #retVal = COUNT(*)
FROM TABLE
WHERE COLUMN = 'Some Value'
IF (#retVal > 0)
BEGIN
--INSERT SOMETHING
END
ELSE
BEGIN
--INSERT SOMETHING ELSE
END
I would do it like so (single line):
IF ((SELECT COUNT(id) FROM table WHERE ....)>18) BEGIN
...do something
You can even do between in a single line
IF ((SELECT COUNT(id) FROM table WHERE ....)between 2 and 20) BEGIN
...do something
END
Your subquery is looking for matches in the entire table. It does not limit the results only to those that are related to the rows affected by the update. Therefore, if the table already has rows matching your condition, the condition will be true on any update that affects other rows.
In order to count only the relevant rows, you should either join the database table to the inserted pseudo-table or use just the inserted table (there is not enough information in your question to be sure which is better).

Check whether a table contains rows or not sql server 2005

How to Check whether a table contains rows or not sql server 2005?
For what purpose?
Quickest for an IF would be IF EXISTS (SELECT * FROM Table)...
For a result set, SELECT TOP 1 1 FROM Table returns either zero or one rows
For exactly one row with a count (0 or non-zero), SELECT COUNT(*) FROM Table
Also, you can use exists
select case when exists (select 1 from table)
then 'contains rows'
else 'doesnt contain rows'
end
or to check if there are child rows for a particular record :
select * from Table t1
where exists(
select 1 from ChildTable t2
where t1.id = t2.parentid)
or in a procedure
if exists(select 1 from table)
begin
-- do stuff
end
Like Other said you can use something like that:
IF NOT EXISTS (SELECT 1 FROM Table)
BEGIN
--Do Something
END
ELSE
BEGIN
--Do Another Thing
END
FOR the best performance, use specific column name instead of * - for example:
SELECT TOP 1 <columnName>
FROM <tableName>
This is optimal because, instead of returning the whole list of columns, it is returning just one. That can save some time.
Also, returning just first row if there are any values, makes it even faster. Actually you got just one value as the result - if there are any rows, or no value if there is no rows.
If you use the table in distributed manner, which is most probably the case, than transporting just one value from the server to the client is much faster.
You also should choose wisely among all the columns to get data from a column which can take as less resource as possible.
Can't you just count the rows using select count(*) from table (or an indexed column instead of * if speed is important)?
If not then maybe this article can point you in the right direction.
Fast:
SELECT TOP (1) CASE
WHEN **NOT_NULL_COLUMN** IS NULL
THEN 'empty table'
ELSE 'not empty table'
END AS info
FROM **TABLE_NAME**