Select Query is not working with in Clause - sql-server

Sql query is not working if we pass value In clause converted from 'Canada,Portugal' to 'Canada','Portugal'
if pass hardcode value In clause 'Canada','Portugal' it works
declare #GeographicalLocation varchar(max)
set #GeographicalLocation ='Canada,Portugal'
set #GeographicalLocation = REPLACE(#GeographicalLocation, ',', ''',''')
set #GeographicalLocation = ''''+#GeographicalLocation+'''';
select ContinentName from [ContinentList] where ContinentId in
(select ContinentId from [CountryList] where [CountryName]
in(#GeographicalLocation)and BaseId is Null)

Because, at the end your where clause looks like:
where [CountryName] in ('''Canada'',''Portugal''')
This string in where caluse should be two separate strings, but it's only one! It should look like this:
where [CountryName] in ('Canada','Portugal')
So, for this situation I'd use something like
where charindex([CountryName], #GeographicalLocation) > 0
In this approach, you don't need to append extra ' to your string variable.
And I'd recommend using case sensitive collation.

Related

SQL CASE Statement Change Column name in THEN clause

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

select from SQL table with concatenation of two string columns

Issue
I want to write a query that will select all from a table where my string value is equal to two columns concatenated together.
This is plain English version:
#MYSTRING varchar(50)
SELECT ALL FROM [FFLOCNP] WHERE COLUMN1 + COLUMN2 = #MYSTRING
I have tried to use the COALESCE but i have never used this before and it is returning me an error:
#CODE varchar(50)
SELECT * FROM [dbo].[FFLOCNP] WHERE COALESCE([LOCTRY], '') || COALESCE([LOCLCN], '') = #CODE
you have to use ISNULL for this.
Use below query may be it helps you.
SELECT * FROM [FFLOCNP] WHERE ISNULL(COLUMN1,'') + ISNULL(COLUMN2,'') = #MYSTRING
Be careful, when using ISNULL instead of COALESCE. ISNULL limits the returned value to the datatype of the first input parameter. In the given example column V1 will be implicitly defined with nvarchar(1), because the longest text in column V1 consists of only one character. ISNULL(V1, [param2]) will therefor return always a one character long string, regardless of the length of the second parameter. In your case ISNULL would work, if you wanted to replace a NULL with an empty string. If you wanted to replace a NULL with a longer string then you MUST use COALESCE instead of ISNULL. COALESCE returns the full string in parameter 2 regardless of the datatype of parameter 1. Apart from this COALESCE is standard SQL whereas ISNULL is a flavor of SQL-Server. Standard SQL should be preferred to T-SQL flavor to get more portable code.
WITH CTE_SRC AS
(
SELECT
[V1]
,[V2]
FROM
(VALUES
(N'A', N'BB')
,(NULL, N'BB')
,(N'A', NULL)
) T([V1],[V2])
)
SELECT
ISNULL([V1], '1234') AS [ISNULL]
,COALESCE([V1], '123') AS [COALESCE]
FROM
CTE_SRC
Result
ISNULL COALESCE
------ --------
A A
1 123
A A

How Do I Use a Variable in a Select Statement?

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'')
'
)

Adding Dyanmic In() Conditions in Sql Server

Facing problem for generating SQL Server Query
In the Following query dynamic conditions are added to check whether value is null or not
Select *
From tblEmployees
where EmployeeName = Case
When #EmployeeName Is Not Null
Then #EmployeeName
Else EmployeeName
End
But I need to add IN () Conditions and the parameter with in the IN () could be null or blank also ,if the parameter /string which is passed to the IN condition is blank then i donot want to add that condition in the query.
So how can i Achieve this.A helping hand will be very useful for me.
Thanks and Regards,
D.Mahesh
Depending on value of your parameter (blank of not), you can create SQL string accordingly.
DECLARE #sqlCommand VARCHAR(1000)
IF(ISNULL(#YourParameter,'')='')
#sqlCommand = 'your query goes here'
ELSE
#sqlCommand = 'your query goes here'
and then, run it using dynamic query execution
EXEC (#sqlCommand)
If not dynamic query then,
SELECT ....
FROM ....
WHERE CASE WHEN ISNULL(#YourParameter,'')='' THEN '' ELSE EmployeeName END IN (ISNULL(#YourParameter,''))
See if this works...
I think the Dynamic query is the best solution, however you could put the "IS NULL" and "IS BLANK" condition in OR with your IN clause.
Something like that
Select *
From tblEmployees
where #EmployeeName is null or EmployeeName in (#EmployeeName)
When #EmployeeName is null, your IN clause will be ignored
If i get this right you have #EmployeeName = 'Name1,Name2,Name3' and you want to get the employees that is named Name1 or Name2 or Name3, also the variable #EmployeeName can be null or contain an empty string.
Instead of using IN you can split the string #EmployeeName on , and store it in a table variable or temporary table. Then you can use that table in a join against tblEmployees to get the rows you need.
There are a lot of posts in S.O. about how to split a string. Here is one recent variant.
Group by sql query on comma joined column
This will work for SQL Server 2005 or later.
declare #EmployeeName varchar(100) = 'Name2,Name3,Name5'
-- Null or empty will have a comma
set #EmployeeName = coalesce(#EmployeeName, '') + ','
-- cteNames splits the string to rows
;with cteNames
as
(
select
left(#EmployeeName, charindex(',', #EmployeeName)-1) as Name,
right(#EmployeeName, len(#EmployeeName)-charindex(',', #EmployeeName)) as EmployeeName
union all
select
left(EmployeeName, charindex(',', EmployeeName)-1) as Name,
right(EmployeeName, len(EmployeeName)-charindex(',', EmployeeName)) as EmployeeName
from cteNames
where charindex(',', EmployeeName) > 1
)
select E.*
from tblEmployees as E
inner join cteNames as N
on E.Name = N.Name or
#EmployeeName = ','
-- #EmployeeName = ',' will give you all names when #EmployeeName is null of empty

How to add column dynamically in where clause

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)

Resources