Condition in sql query - sql

I want to insert in sql query something like that:
Select * from Users where id=[if #userId>3 then #userId else "donnt use this condition"] and Name=[switch #userId
case 1:"Alex"
case 2:"John"
default:"donnt use this condition"];
How can i do it?
yet another similar question
When showAll is false it works ok but when showAll is true it returns nothing. Why and how to make it working right? IsClosed column has a bit type.
Select * from orders where IsClosed=CASE WHEN #showAll='false' THEN 'false' ELSE NULL END;

This will perform horribly:
Select *
from Users
where (#userid > 3 AND id = #userId)
OR (#userId BETWEEN 1 AND 2 AND name = CASE
WHEN #userId = 1 THEN 'Alex'
ELSE 'John'
END)
The best performing option is dynamic SQL:
SQL Server 2005+
DECLARE #SQL NVARCHAR(4000)
SET #SQL = 'SELECT u.*
FROM USERS u
WHERE 1 = 1 '
SET#SQL = #SQL + CASE
WHEN #userId > 3 THEN ' AND u.id = #userId '
ELSE ''
END
SET#SQL = #SQL + CASE #userId
WHEN 1 THEN ' AND u.name = ''Alex'' '
WHEN 2 THEN ' AND u.name = ''John'' '
ELSE ''
END
BEGIN
EXEC sp_executesql #SQL, N'#userId INT', #userId
END
For more info on SQL Server's dynamic SQL support, read "The Curse and Blessings of Dynamic SQL"

Select *
from Users
where id = CASE WHEN #userId>3 THEN #userId ELSE NULL END
OR name = CASE WHEN #userId = 1 THEN 'Alex' WHEN #UserId = 2 THEN 'John' ELSE NULL END

Please try this:
select *
from Users
where id = (case when #userId > 3 then #userId
else id end)
and Name = (case cast(#userId as varchar)
when '1' then 'Alex'
when '2' then 'John'
else Name end)
Or I think this will perform better:
select aa.*
from (select *
, case when #userId > 3 then #userId
else id end as UserID
, case cast(#userId as varchar)
when '1' then 'Alex'
when '2' then 'John'
else Name end as UserName
from Users) aa
where aa.id = aa.UserID
and aa.Name = aa.UserName
You might want to define each field that you only need on your select, instead of using asterisk(*).

Related

How to set a variable and check it for null both in the "case when" conditions SQL

I have problem with this piece of code.
I need to do something like this:
DECLARE #UserID INT
...
CASE
WHEN (#UserID = (SELECT TOP 1 UserPk FROM Users WHERE Name= 'JoeDoe')) IS NULL
THEN 0
ELSE 1
END
I need set #UserID for some other next steps and at the same time need to check (SELECT TOP 1 UserPk FROM Users WHERE Name = 'JoeDoe') for null.
Thanks for help.
like this?
IF EXISTS (SELECT UserPk FROM Users WHERE Name= 'JoeDoe')
SET #UserID = 0;
ELSE
SET #UserID = 1;
Perhaps just an ISNULL?
SET #UserID = ISNULL(SELECT UserPk FROM Users WHERE Name= 'JoeDoe'),0);
I would suggest using EXISTS:
DECLARE #UserID INT;
SET #UserId = (CASE WHEN EXISTS (SELECT 1 FROM Users WHERE Name= 'JoeDoe')
THEN 1 ELSE 0
END);
I'm not sure why you are calling this column #UserId. It appears to be a flag on the presence of the name.
Just use below:
DECLARE #UserID INT
SET #UserID = ISNULL((SELECT TOP(1) 1 FROM Users WHERE Name= 'JoeDoe'), 0)
Print #UserID

SQL CASE wrong output

I have this weird encounter using CASE in sql 2014.
This is my query:
SELECT (CASE WHEN dbo.GetFunctionAge(C.Birthdate) = 0
THEN '' ELSE dbo.GetFunctionAge(C.Birthdate)
END) AS Age
,dbo.GetFunctionAge(C.Birthdate)
,c.Birthdate
FROM Client C
WHERE ClientID = '34d0d845-e3a6-4078-8936-953ff3378eac'
this is the output:
Here is the GetFunctionAge function if you might ask.
IF EXISTS (
SELECT *
FROM dbo.sysobjects
WHERE ID = OBJECT_ID(N'[dbo].[GetFunctionAge]') AND
xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION [dbo].[GetFunctionAge]
GO
CREATE FUNCTION [dbo].[GetFunctionAge](#BirthDate DATETIME)
RETURNS INT
AS
BEGIN
DECLARE #Age INT
IF(#BirthDate = '1753-01-01 00:00:00.000')
BEGIN
SET #Age = 0
END
ELSE
BEGIN
SET #Age = DATEDIFF(hour,#BirthDate,GETDATE())/8766
END
RETURN #Age
END
GO
Question:
Why is Column Age in my output is 0which should be ''?
I added (No column name) to show that its output is 0 so my expected output base from my case condition is '' not 0
I didn't receive any error regarding inconsistency of data so why is case behaving like that?
Thanks for those who could clarify this to me.
SELECT
(CASE
WHEN a.ageint = 0 THEN ''
ELSE cast(a.ageint as varchar(3))
END) AS Age
, a.ageint
, c.Birthdate
FROM Client as C
CROSS APPLY (
SELECT
ISNULL(dbo.GetFunctionAge(C.Birthdate), 0) AS ageint
) AS a
WHERE ClientID = '34d0d845-e3a6-4078-8936-953ff3378eac'
;
You can cast it into varchar so you can return ' '.
SELECT (CASE WHEN dbo.GetFunctionAge(C.Birthdate) = 0
THEN '' ELSE Cast(dbo.GetFunctionAge(C.Birthdate) as varchar(5))
END) AS Age
,dbo.GetFunctionAge(C.Birthdate)
,c.Birthdate
FROM Client C
WHERE ClientID = '34d0d845-e3a6-4078-8936-953ff3378eac'
But If you wish to remain your Age column in data type int.
You could just use NULL instead of ' '

SQL Query filter with custom field

Below code are use to detect if there exist userid=1 followerid=2 AND userid=2 followerid=1, then the custom column 'bool' will return TRUE.
However, somehow i can't get rid the extra row.
Any better suggestion or recommendations are appreciated. Thank you.
SELECT DISTINCT a.id, a.userid, a.followerid,
CASE WHEN b.userid=a.followerid AND b.followerid=a.userid
THEN 'TRUE' ELSE 'FALSE' END AS bool
FROM tableUserfollow AS a, tableUserfollow AS b
where a.userid=1
tableUserFollow:
id userid followerid
1 1 2
2 3 4
3 1 4
4 5 1
5 2 1
The output result should be:
1 1 2 TRUE
3 1 4 FALSE
instead of this:
1 1 2 FALSE
1 1 2 TRUE
3 1 4 FALSE
If you want to know if the reciprocal relationship is present, then I think the simplest way is using a correlated subquery, left join, or outer apply:
select uf.*, coalesce(flag, 'FALSE') as
from tableUserfollow uf outer apply
(select 'TRUE' as flag
from tableUserfollow uf2
where uf2.userId = uf.followerId and uf2.follwerId = uf.userId
) f;
The join would look like:
select uf.*,
(case when uf2.userId is null then 'FALSE' else 'TRUE' end)
from tableUserfollow uf left join
tableUserfollow uf2
on uf2.userId = uf.followerId and uf2.follwerId = uf.userId
DECLARE #sql AS nvarchar(MAX);
DECLARE #Search AS nvarchar(MAX);
DECLARE #AllFiels Varchar(max);
DECLARE #FixedField Varchar(max);
SET #FixedField=( SELECT
ISNULL(( STUFF(
(
SELECT ', '+(a.value) FROM vwCustomColumns a
WHERE a.Name IN (SELECT items FROM dbo.Split(CustomReports.ReportFixedFields,',') )
FOR XML path('')
)
, 1,1,'')) ,'cR.ContractID [Contract ID]') FixedField
FROM CustomReports WHERE CustomReportId=#CustomReportId )
SET #AllFiels=#FixedField;
SET #sql ='SELECT count(*) OVER() AS Maxcount ,'+#AllFiels+'
FROM vwRequestLatest cR
INNER JOIN MasterUsers ON MasterUsers.UsersId = cR.Addedby
LEFT OUTER JOIN RequestTemplate cte ON cte.ContractTemplateId=cR.RequestTemplateId
LEFT OUTER JOIN CountryMaster co ON co.CountryId=cR.CountryId
ORDER BY
';
IF (#SortColumn = '')
BEGIN
IF (#Direction = 0)
SET #sql =#sql + ' cR.RequestId ASC '
ELSE
SET #sql =#sql + ' cR.RequestId DESC '
END
ELSE IF (#SortColumn = 'Request ID')
BEGIN
IF (#Direction = 0)
SET #sql =#sql + ' cR.RequestId ASC '
ELSE
SET #sql =#sql + ' cR.RequestId DESC '
END
SET #sql =#sql +'OFFSET ( '+CONVERT(VARCHAR(100),#PageNo)+' - 1 ) * '+CONVERT(VARCHAR(100),#RecordsPerPage)+' ROWS FETCH NEXT '+CONVERT(VARCHAR(100),#RecordsPerPage)+' ROWS ONLY'
EXEC(#sql);

IN Condition Issue in SQL Server

I want to use multiple inputs in a procedure in IN condition. How can I do this?
Below is my query code.
Declare #iM_ID varchar(100)
set #iM_ID='20,22,24,25'
select #iM_ID
SELECT M.M_ID,
SUM(CASE WHEN CT_ID=1
THEN 1
ELSE 0 END) AS "Secret_Coupons",
SUM(CASE WHEN CT_ID=2
THEN 1
ELSE 0 END) AS "Hot_Coupons"
FROM C_Master
INNER JOIN M_Master
ON C_Master.M_ID=M_Master.M_ID
and datediff(hh,getutcdate(),End_Datetime)>0
and M_Master.M_ID in (#iM_ID)
GROUP BY M_Master.M_ID
Try like this
DECLARE #sql AS VARCHAR(MAX)
Declare #iM_ID varchar(100)
SET #iM_ID='20,22,24,25'
SET #sql = 'SELECT M.M_ID,SUM(CASE WHEN CT_ID=1 THEN 1 ELSE 0 END) AS "Secret_Coupons",
SUM(CASE WHEN CT_ID=2 THEN 1 ELSE 0 END) AS "Hot_Coupons"
FROM C_Master INNER JOIN M_Master ON C_Master.M_ID=M_Master.M_ID
AND datediff(hh,getutcdate(),End_Datetime)>0 AND
M_Master.M_ID IN ( ' + #iM_ID + ')
GROUP BY M_Master.M_ID'
EXECUTE #sql

Assign to a T-SQL variable from a CASE statement

I'd like to assign some variables inside a query that uses CASE statements for it's columns. Not quite sure how to do this, having trouble finding the right syntax.
This is what I have so far, but it's got syntax errors.
-- set #theID and #theName with their appropriate values
select top (1)
#theID = (Case when B.ID IS NULL then A.ID else B.ID END) ,
#theName = (Case when B.Name IS NULL then A.Name else B.Name END)
from B left join A on A.ID = B.ID where ...
What's the correct place/way to stick those variables in there?
The example you've given should work. You can assign to variables from a case statement. Just pretend that the entire CASE..WHEN..THEN..ELSE..END block is a field. Here is a generic example:
declare #string1 nvarchar(100) = null
declare #string2 nvarchar(100) = null
select
#string1 = case when 1=1 then 'yes' else 'no' end
,#string2 = case when 1=0 then 'yes' else 'no' end
print 'string1 = ' + #string1
print 'string2 = ' + #string2
Gives:
string1 = yes
string2 = no
Can you tell us what specific error(s) you are getting?
You could probably do this more easily using ISNULL or COALESCE:
select top (1)
#theID = ISNULL(B.ID, A.ID),
#theName = ISNULL(B.Name, A.Name),
from B left join A on A.ID = B.ID where ...
DECLARE #SmallBlindSeatId INT
DECLARE #BigBlindSeatId INT
DECLARE #DealerSeatId INT
DECLARE #NextTurn INT
SELECT #DealerSeatId=( CASE WHEN BlindsInfo=1 THEN SeatId ELSE #DealerSeatId END ),
#SmallBlindSeatId=( CASE WHEN BlindsInfo=2 THEN SeatId ELSE #SmallBlindSeatId END),
#BigBlindSeatId=( CASE WHEN BlindsInfo=3 THEN SeatId ELSE #BigBlindSeatId END),
#NextTurn=( CASE WHEN NEXTTURN=1 THEN SeatId ELSE #NextTurn END)
FROM ABC WHERE TESTCASEID=1
PRINT(#DealerSeatId)
PRINT(#SmallBlindSeatId)
PRINT(#BigBlindSeatId)
PRINT (#NextTurn)