I want to include column in where clause depending on the condition.
e.g
select * From emp
where id=7,
and if(code is not null) then code=8;
how can i do this in sql server
If I understand you correct, you could make use of COALESCE.
COALESCE()
Returns the first nonnull expression
among its arguments.
SQL Statement
SELECT *
FROM emp
WHERE id=7
AND code = COALESCE(#code, code)
If code is a column rather than a variable the query in your question would be rewritten as follows.
SELECT *
FROM emp
WHERE id=7 AND (code IS NULL OR code=8)
You'll probably have to create a query dynamically, as a string, and then use the Execute method to actually execute it. This approach has some potentially optimization issues, but it's commonly done. You might wan to Google T-SQL Dynamic Query, or something like that.
Also use this in case of Null value in #var1.
Select * from ABC where Column1 = isNull(#var1, Column1)
here is the example:
declare #SQL varchar(500)
declare #var1 int
set int = 1
set #SQL = 'Select * from ABC Where 1 = 1'
if(#var1 = 1)
set #SQL + #SQL ' And column1 = ' #var1
exec(#SQL)
You can use COALESCE function.
Well,
I don't know if i understood your question, but i guess that you want to include the value of the code column in the results.
If i'm right it can be done in the select part instead of the where clause. i. e.
Select ..., case when code is not null then 8 else code end as code from emp where id = 7
The other interpretation is that you want to filter rows where code <> 8,that would be
Select * from emp where id = 7 and (code is null OR code = 8)
Related
We have a table LogicalTableSharing as follows:
For a specific requirement, we need to take PhysicalCompany of each TableCode into a variable.
We tried a case-based query as follows:
declare #tablecode varchar(50)
declare #inputcompany varchar(50)
declare #query nvarchar(2500)
set #inputcompany= 91
set #query = '
select '''+#inputcompany+''' AS inputcompany,
CASE WHEN lts.TableCode = ''tsctm005'' THEN lts.PhysicalCompany ELSE NULL END as tsctm005_company,
CASE WHEN lts.TableCode = ''tccom000'' THEN lts.PhysicalCompany ELSE NULL END as tccom000_company
from LogicalTableSharing lts
where lts.LogicalCompany = '''+#inputcompany+'''
'
EXEC sp_executesql #query
which obviously gives the result as
The desired output is
What is the right approach?
Try subqueries in a FROM-less SELECT. For performance you want an index on (logicalcompany, tablecode) (or the other way round depending on which is more selective).
SELECT #inputcompany inputcompany,
(SELECT TOP 1
physicalcompany
WHERE logicalcompany = #inputcompany
AND tablecode = 'tsctm005'
ORDER BY <some criteria>) tsctm005_company,
(SELECT TOP 1
physicalcompany
WHERE logicalcompany = #inputcompany
AND tablecode = 'tccom000'
ORDER BY <some criteria>) tccom000_company;
You should find <some criteria> to order by in case of multiple possible rows to decide which one takes precedence. Unless you just want a random one possibly each time you run the query another one, that is.
I need to fetch max length of First_name and put it into #sq i am getting an error.
Declare #sq nvarchar(max)
Set #sq=''
SELECT MAX(LEN(FIRST_NAME)) FROM #table1
Drop table #t
SELECT CASE WHEN LEN(SEQ_NUM) = 0 THEN NULL ELSE SEQ_NUM END AS REC_NUM,
CASE WHEN LEN(FIRST_NAME) = 0 THEN NULL ELSE CONVERT(CHAR(Select #sq)),RTRIM(UPPER(FIRST_NAME))) END AS FIRST_NAME
into #t
from #tabel1
There's a few problem with this SQL. If we start with the first statement:
Set #sq=''SELECT MAX(LEN(FIRST_NAME)) FROM #table1
You have a couple of wayward single quotes here ('); not sure what they're doing. Secondly, if you're assigning a variables value from a dataset, the syntax is SELECT {Variable} = {expression} [,{Variable} = {expression} [,...]] FROM {etc} Thus you get:
SELECT #sq = MAX(LEN(FIRST_NAME))
FROM #table1;
The next statement, well, that's a mess. Firstly, there's also a wayward right parenthesis ()) here: RTRIM(UPPER(FIRST_NAME))) There should only be 2.
The expression CONVERT(CHAR(Select #sq)) is very wrong. CONVERT require 2 parameters, but only has one, and CHAR would return an character for the appropriate number provided. I.e. CHAR(65) returns A. I suspect you mean CONVERT(char,#sq) (you should really be declaring a length here!), however, #sq is already an nvarchar(max) (which is also pointless, as it's being assigned the value of an int). Thus I literally have no idea what you're trying to achieve here.
You need to assign the variable, like this:
Declare #sq int --LEN returns an int, not a varchar!
SELECT #sq = MAX(LEN(FIRST_NAME))
FROM #table1
Is there anyway that I can change column name through THEN clause in CASE STATEMENT. This is how my code looks but it is not working.
SELECT
CASE
WHEN #IDWeeklySpecial = '107'
THEN
CASE
WHEN ISNULL(v.blnLeftHandDrive, 0) = 1
THEN [HANDEDNESS] = 'LHD'
ELSE [HANDEDNESS] = 'RHD'
ELSE
CASE
WHEN ISNULL(v.blnLeftHandDrive, 0) = 1
THEN STEERING = 'LHD'
ELSE STEERING = 'RHD'
END
END
I want this result
My Ideal Result
Is this achievable? If so how?
No, it's not possible... if you are asking about dynamically modifying the column name in the resultset.
The CASE expression returns a value. To a specify the column name in the resultset, assign an alias.
SELECT CASE ... END AS mycolname
, ...
FROM ...
The column name is determined when the statement is parsed and prepared. The execution of the statement cannot modify the column name.
(It's possible I didn't understand the question. It's not clear what OP is tying to achieve.)
case is an expression. You can name the column before or after an expression, but not in the middle.
Also, a SQL statement needs to return a fixed set of columns, including the column name.
So, you cannot do what you want with a simple SQL statement. You could use dynamic SQL:
declare #sql nvarchar(max);
set #sql = '
SELECT (CASE WHEN COALESCE(v.blnLeftHandDrive, 0) = 1
THEN 'LHD'
ELSE 'RHD'
END) as [columnname]
. . . ';
set #sql = replace(#sql, '[columnname]',
(case when #IDWeeklySpecial = '107' then 'HANDEDNESS' else 'STEERING' end)
);
exec sp_executesql #sql;
Note that the . . . is for the rest of your SQL query.
I can't digest your select statement, but assume its inline case
SELECT item_name = CASE WHEN item_name = 'sometext' THEN item_id ELSE item_name END AS MyColumnName
It is not possible to assign differing column names in your query, because all vertical data values in the result set belong to the same column.
If you are just trying to alias a column name while using the CASE expression, ensure that the AS is used after the END keyword. Others have mentioned this, but it was the problem in my case. Changed it to something like this and it worked:
CASE
WHEN table1.Name LIKE '%John%' THEN 'Some John Person'
WHEN table1.Name <> 'NULL' THEN table1.Name
ELSE 'Nobody'
END AS NewAliasColumnName
When I run the following code I get the error : Incorrect syntax near '#num_to_remove'.
Any idea why this doesn't work?
Thanks in advance,
Matt
DECLARE #num_to_remove INT
SET #num_to_remove = 2
-- get em_ids for records to delete
WITH em_ids
AS (SELECT TOP #num_to_remove em_id
FROM irs_self_cert_em sc
WHERE sc.date_cert_loc IS NULL
AND sc.date_first_cert_email_sent < '2014-10-03')
SELECT * FROM em_ids
In regular tSQL, you can only use variables to represent values, not column names or other objects. I know the numeric value for a "TOP" clause seems like it should qualify but it doesn't.
To use a variable in this way, you have to do Dynamic SQL.
Try this (Note: I haven't tested it. You can try similar this)
DECLARE #num_to_remove INT
SET #num_to_remove = 2
-- get em_ids for records to delete
EXEC
(
'WITH em_ids
AS (SELECT TOP ' + CAST(#num_to_remove AS varchar(10) + 'em_id
FROM irs_self_cert_em sc
WHERE sc.date_cert_loc IS NULL
AND sc.date_first_cert_email_sent < ''2014-10-03'')
'
)
What is the best way to include an input param in the WHERE clause but exclude it if it is null?
There are a number of ways I believe, but I can't seem to remember then.
Also could I use the COALESCE()? But I think this is only for SELECTing values?
Edit
To clarify, let's say a variable called #code ="1" then my where would be Where type='B' AND code = #code but if #code is null then I only want Where type='B' - notice the missing code = #code.
You can use IsNull
where some_column = IsNull(#yourvariable, 'valueifnull')
EDIT:
What you described in the comment can be done like:
where (#code is null or code = #code)
Here's another approach
SELECT * FROM Thingies WHERE ( #thingId IS NULL OR ThingID = #thingId )
How about
WHERE (Column1 = #Var1 OR #Var1 IS NULL)
AND (Column2 = #Var2 OR #Var2 IS NULL)
I’d like to suggest a solution which I found on another site:
SELECT * FROM Thingies
WHERE ThingID = isnull(#ThingId,ThingID)
With this solution if the user selects null for your parameter then your query will return all the rows as the result.
This question really helped me with a similar issue that had a few of us scratching our heads for a bit. I only write it up in case somebody else tries the same approach and cannot figure out why it does not work.
I was trying to only evaluate a part of a multipart WHERE clause if the #Parameter was not null. I tried to do this as below but always had no rows returned if #Parameter was null.
DECLARE #Parameter int = null;
SELECT * FROM TABLE
WHERE [AlternateID] is not null
AND (#Parameter is not null AND [AlternateID] = #Parameter)
I incorrectly thought that (#Parameter is not null AND [AlternateID] = #Parameter) would simply not form part of the full WHERE clause is #Parameter was null. However it was making the entire WHERE clause return false. The remedy was to add an OR 1=1 as below:
WHERE [AlternateID] is not null
AND (#Parameter is not null AND [AlternateID] = #Parameter OR 1=1)
Of course the approach outlined by Ali (not enough reputation to upvote) solves this more efficiently.
WHERE [AlternateID] is not null
AND [Partner_Customer_ID] = ISNULL(#Parameter, [Partner_Customer_ID])
You can use ISNULL(), or check for nulls explicitly as others have mentioned. This should be OK as long as you have no more than 1 or 2 optional input parameters. But if there are more parameters, this approach would be very inefficient as the indexes you create on those columns won't be used as you would expect. In such a case i would recommend you to use dynamic SQL. Here is an excellent article that explains why http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/
I think this will help
#id
#name
SELECT [Id],[Name] FROM [Person]
WHERE Id = #id and ISNULL(#name, Name)
This will allow you just ignore the Name condition if it is null