IN Condition Issue in SQL Server - sql

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

Related

How to use like clause over string separated with comma inside case statement

DECLARE #IsSearch_ BIT;
SET #IsSearch_ ='True'
DECLARE #Organization_ VARCHAR(100);
SET #Organization_ ='111,111A'
select *
from VYC20 C20
where (#Organization_ IS NULL)
OR (1 = CASE #IsSearch_
WHEN 0 THEN (CASE WHEN #Organization_ IS NOT NULL
AND C20.ORG IN
(select value
from STRING_SPLIT(#Organization_, ','))
THEN 1 ELSE 0 END)
WHEN 1 THEN (CASE WHEN C20.ORG like #Organization_ + '%'
THEN 1 ELSE 0 END)
ELSE 0 END)
In the above query the 1st case WHEN 0 statement with IN clause gives the correct record, but the WHEN 1 THEN gives me 0 records, can someone please help me how to apply like clause with string separated with comma.
It looks like what you actually want is to use LIKE after splitting
DECLARE #IsSearch_ BIT = 1;
DECLARE #Organization_ VARCHAR(100) = '111,111A';
SELECT *
FROM VYC20 C20
WHERE #Organization_ IS NULL
OR (#IsSearch_ = 0 AND
C20.ORG IN
(SELECT s.value
FROM STRING_SPLIT(#Organization_, ',') s))
OR (#IsSearch_ = 1 AND
EXISTS (SELECT 1
FROM STRING_SPLIT(#Organization_, ',') s
WHERE C20.ORG LIKE s.value + '%'));
I strongly advise you to do this in a set-based fashion and use a table variable or Table Parameter
DECLARE #IsSearch_ BIT = 1;
DECLARE #Organization_ TABLE (value VARCHAR(100));
INSERT #Organization_ VALUES('111'),('111A');
SELECT *
FROM VYC20 C20
WHERE #IsSearch_ = -1 -- include all
OR (#IsSearch_ = 0 AND
C20.ORG IN
(SELECT s.value
FROM #Organization_ s))
OR (#IsSearch_ = 1 AND
EXISTS (SELECT 1
FROM #Organization_ s
WHERE C20.ORG LIKE s.value + '%'));

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

How to Convert Centesimal to Sexagesimal

I have this query: I need convert the centesimal value from the database to sexagesimal (minutes)
SELECT
DISTINCT RD_MAT,
SUM(CASE WHEN RD_PD IN ('421') THEN RD_HORAS ELSE 0 END) AS 'ATRASOS',
SUM(CASE WHEN RD_PD IN ('420') THEN RD_HORAS ELSE 0 END) AS 'FALTAS',
SUM(CASE WHEN RD_PD IN ('084') THEN RD_HORAS ELSE 0 END) AS 'H.EXTRA 100%',
SUM(CASE WHEN RD_PD IN ('080') THEN RD_HORAS ELSE 0 END) AS 'H.EXTRA 50% ',
SUM(CASE WHEN RD_PD IN ('082') THEN RD_HORAS ELSE 0 END) AS 'H.EXTRA NOTURNA'
FROM SRD020
INNER JOIN SRV020 ON RD_PD = RV_COD
AND SRV020.D_E_L_E_T_ <> '*'
AND SRD020.D_E_L_E_T_ <> '*'
AND RD_MAT = '000123'
WHERE LEFT(RD_DATPGT,6) = '201304'
GROUP BY RD_MAT
The return of H.EXTRA 100% in centesimal is 16:53. But in minutes is 16:49.
Example: 40 + 40 = 80 in centesimal. 40 + 40 = 1:20 in sexagesimal. I need this value.
So, it looks like you're going for something like this. I'm casting to VARCHAR for output purposes, which you of course do not have to do.
DECLARE #value1 INT, #value2 INT
SET #value1 = 40
SET #value2 = 50
SELECT CAST(FLOOR((#value1+#value2)/60) AS VARCHAR(50)) + ':' + CAST((#value1+#value2)%60 AS VARCHAR(50))
Declare #h Varchar(5)='16:53'
Select Cast(DateAdd(SS,CAST(REPLACE(#h,':','.') as Float)*60,0) as Time)
>>> 00:16:31.0000000

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)

Condition in sql query

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(*).