SQL Query filter with custom field - sql

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

Related

Concatenate query string in procedure having case statement with parameter

I need to append below select query set with another set query based on condition
DECLARE #queryString VARCHAR(1000);
-- Insert statements for procedure here
Set #queryString ='SELECT
CASE
WHEN d.sno IS NOT NULL THEN 'y'
ELSE NULL
END
amendment_type,
u.user_login_id [User],
role_name [Role],
u.user_name [Name],
a.companyname +':<br>('+b.branch+')' [Agent/Branch],
u.last_login_pc+'('+u.ip_address+')<br> Login Time: '+cast(u.last_login AS varchar(50)) [Last Login],
u.lock_status [Lock/Unlock],
CASE
WHEN u.lock_status='y' THEN 'Locked - '+ u.lock_by
WHEN datediff(d,u.last_login,getdate())>u.lock_days
AND isnull(u.lock_days,0)>0 THEN 'Locked - Day Exceed'
WHEN u.active_session IS NULL
AND isnull(u.lock_status,'n')='n' THEN 'Not Login'
ELSE 'Active'
END
[Status],
u.*,
a.agentcan,
b.branch,
b.branchcodechar,
NULL branchcan
FROM agentsub u
JOIN agentbranchdetail b
ON u.agent_branch_code=b.agent_branch_code
JOIN agentdetail a
ON b.agentcode=a.agentcode
LEFT OUTER JOIN application_role_agent_user r
ON u.user_login_id=r.user_id
LEFT OUTER JOIN application_role p
ON r.role_id=p.role_id
LEFT OUTER JOIN agentsub_amendment d
ON d.agent_user_id=u.agent_user_id
WHERE 1=1'
IF (#loginId !=null)
BEGIN
SET #queryString =#queryString + 'and u.user_login_id like ('+ #loginId +')'
END
SET #queryString =#queryString +'order by u.user_login_id,a.companyname,b.branch'
EXEC #queryString
First... Your query as it stands (via notepad++) is 1,731 characters, so it wont fit into a varchar(1000)
Second... You need to address some escaping issues with your query; e.g.
WHEN d.sno IS NOT NULL THEN 'y'
should probably be
WHEN d.sno IS NOT NULL THEN ''y''
Third... google/investigate sp_executesql and parameters
Finally... as #Panagiotis Kanavos says, Don't concatenate anything (see Third...); you need to look up "sql injection"
#uberbloke is correct regarding query length.
EXEC sp_executesql with multiple parameters link give you solution for dynamic query to pass parameter values.
Please check below updated query code.
DECLARE #queryString NVARCHAR(MAX);
-- Insert statements for procedure here
Set #queryString =
'SELECT
CASE
WHEN d.sno IS NOT NULL THEN ''y''
ELSE NULL
END
amendment_type,
u.user_login_id [User],
role_name [Role],
u.user_name [Name],
a.companyname + '':<br>('' + b.branch) [Agent/Branch],
u.last_login_pc + ''('' + u.ip_address + '')<br> Login Time: '' + cast(u.last_login AS varchar(50)) + '' [Last Login],
u.lock_status [Lock/Unlock],
CASE
WHEN u.lock_status = ''y'' THEN ''Locked - '' + u.lock_by
WHEN datediff(d,u.last_login,getdate()) > u.lock_days AND (u.lock_days,0) > 0 THEN ''Locked - Day Exceed''
WHEN u.active_session IS NULL AND isnull(u.lock_status,''n'') = ''n'' THEN ''Not Login''
ELSE ''Active''
END [Status],
u.*,
a.agentcan,
b.branch,
b.branchcodechar,
NULL branchcan
FROM agentsub u
JOIN agentbranchdetail b ON u.agent_branch_code = b.agent_branch_code
JOIN agentdetail a ON b.agentcode = a.agentcode
LEFT OUTER JOIN application_role_agent_user r ON u.user_login_id = r.user_id
LEFT OUTER JOIN application_role p ON r.role_id = p.role_id
LEFT OUTER JOIN agentsub_amendment d ON d.agent_user_id = u.agent_user_id
WHERE 1 = 1 '
IF (#loginId !=null)
BEGIN
SET #queryString = #queryString + 'and u.user_login_id like ('+ #loginId + ')'
END
SET #queryString = #queryString + ' order by u.user_login_id,a.companyname,b.branch'
EXEC sp_executesql #queryString
I am getting below error:

Case when in Select, Left Join and Group By

how can i archive the following?
If #chk = 0 then include 4th Column in result else keep only 3 Columns,
and if 4th Column is selected then Left join is needed for that 4th column,
and include that 4th column in group by
DECLARE #chk AS INT= 0;
SELECT a.Ledgerid,
b.LedgerCity,
CASE WHEN #chk = 0 THEN SUM(a.TotalAmount) ELSE SUM(a.NetAmount) END,
CASE WHEN #chk = 0 THEN c.ledgername END (is it possilbe to completly do not have this column if #chk <> 0)
FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID
LEFT JOIN LedgerMaster AS C ON A.LedgerID = C.LedgerID --This left join is required only if #chk=0, same logic is there in above select statement
GROUP BY A.LedgerID,
B.LedgerCity;
C.LedgerName; -- this 3rd group required only if #chk=0
some posts suggested how to use case when in Group by. I tried "group by case when #chk=0 then a.Ledgerid,b.Ledgercity,c.LedgerName else a.Ledgerid,b.Ledgercity END; but this did not work
Use IF .. ELSE block
IF #chk = 0
BEGIN
SELECT a.Ledgerid,
b.LedgerCity,
CASE WHEN #chk = 0 THEN SUM(a.TotalAmount) ELSE SUM(a.NetAmount) END,
CASE WHEN #chk = 0 THEN c.ledgername END
FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID
LEFT JOIN LedgerMaster AS C ON A.LedgerID = C.LedgerID --This left join is required only if #chk=0, same logic is there in above select statement
GROUP BY A.LedgerID, B.LedgerCity, C.LedgerName;
END
ELSE
BEGIN
SELECT a.Ledgerid,
b.LedgerCity,
CASE WHEN #chk = 0 THEN SUM(a.TotalAmount) ELSE SUM(a.NetAmount) END
FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID
GROUP BY A.LedgerID, B.LedgerCity;
END
If you are sure, that no one from outside of the database can run your query and perform sql-injection, just use the simple dynamic-sql statement
DECLARE #sql AS NVARCHAR(MAX);
DECLARE #chk AS INT= 0;
set #sql = N'SELECT a.Ledgerid,
b.LedgerCity, ' +
CASE WHEN #chk = 0 THEN 'SUM(a.TotalAmount) ' ELSE 'SUM(a.NetAmount) ' END +
CASE WHEN #chk = 0 THEN ', c.ledgername ' ELSE ' ' END +
'FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID ' +
CASE WHEN #chk=0 THEN 'LEFT JOIN LedgerMaster AS C ON A.LedgerID = C.LedgerID ' ELSE '' END +
'GROUP BY A.LedgerID,
B.LedgerCity' +
CASE WHEN #chk = 0 THEN ', C.LedgerName;' ELSE ';' END;
exec sp_executesql #sql

Convert all rows into different in sql server

I have a stored procedure that is showing a list of doctors and their details based on the sub-department they belong to. Below is the stored proc:
CREATE PROCEDURE SP_BILL_FOOTER_DOCTOR
#subDepartmentId int
AS
BEGIN
SELECT HETC_MST_EMPLOYEE.EMPLOYEE_NAME,
HETC_PAR_EMPLOYEE_TYPE.EMPLOYEE_TYPE_NAME,
HETC_MST_DOCTOR_SPECIALITY.DOCTOR_SPECIALITY_DESCRIPTION,
HETC_MST_SUB_DEPARTMENT.SUB_DEPARTMENT_NAME,
HETC_MST_EMPLOYEE.DOCTOR_SIGNATURE,
CASE WHEN HETC_MST_EMPLOYEE.DOCTOR_SIGNATURE = ''
THEN ''
ELSE ISNULL(SIGNATURE_PATH.DOCUMENT_PATH,'')+ HETC_MST_EMPLOYEE.DOCTOR_SIGNATURE
END AS DOCTOR_SIGNATURE_PIC
FROM HETC_MST_EMPLOYEE
INNER JOIN HETC_PAR_EMPLOYEE_TYPE
ON HETC_PAR_EMPLOYEE_TYPE.EMPLOYEE_TYPE_ID = HETC_MST_EMPLOYEE.EMPLOYEE_TYPE_ID
INNER JOIN HETC_MST_DOCTOR_SPECIALITY
ON HETC_MST_DOCTOR_SPECIALITY.DOCTOR_SPECIALITY_ID = HETC_MST_EMPLOYEE.DOCTOR_SPECIALITY_ID
INNER JOIN HETC_MST_DOCTOR_DEPARTMENT
ON HETC_MST_DOCTOR_DEPARTMENT.EMPLOYEE_ID = HETC_MST_EMPLOYEE.EMPLOYEE_ID
INNER JOIN HETC_MST_SUB_DEPARTMENT
ON HETC_MST_SUB_DEPARTMENT.SUB_DEPARTMENT_ID = HETC_MST_DOCTOR_DEPARTMENT.SUB_DEPARTMENT_ID
LEFT JOIN (SELECT DOCUMENT_PATH
FROM HETC_MST_DOCUMENT_PATH
INNER JOIN HETC_MST_TYPE_OF_ATTACHMENT
ON HETC_MST_DOCUMENT_PATH.TYPE_OF_DOCUMENT_ID = HETC_MST_TYPE_OF_ATTACHMENT.TYPE_OF_DOCUMENT_ID
WHERE HETC_MST_TYPE_OF_ATTACHMENT.TYPE_OF_DOCUMENT_CODE='DSI') AS DOC_SIGNATURE_PIC
ON 1=1
WHERE HETC_MST_SUB_DEPARTMENT.SUB_DEPARTMENT_ID = #subDepartmentId
END
Below is the link of the output that follows when procedure executes :
I want to know is it possible to convert the rows in different column. Like the output has 6 columns and 2 rows, I want all the data in 1 row with 12 columns. Below is the sample output:
It would be of great help if somebody could guide me on how to do it. I have understood that by using Pivot in Sql, I can achieve this, but none I have found to my specific case.
Please have a look at updated code below:
select *, row_number() over(order by employee_name) rownum into #a from (
SELECT HETC_MST_EMPLOYEE.EMPLOYEE_NAME,
HETC_PAR_EMPLOYEE_TYPE.EMPLOYEE_TYPE_NAME,
HETC_MST_DOCTOR_SPECIALITY.DOCTOR_SPECIALITY_DESCRIPTION,
HETC_MST_SUB_DEPARTMENT.SUB_DEPARTMENT_NAME,
HETC_MST_EMPLOYEE.DOCTOR_SIGNATURE,
CASE WHEN HETC_MST_EMPLOYEE.DOCTOR_SIGNATURE = ''
THEN ''
ELSE ISNULL(SIGNATURE_PATH.DOCUMENT_PATH,'')+ HETC_MST_EMPLOYEE.DOCTOR_SIGNATURE
END AS DOCTOR_SIGNATURE_PIC
FROM HETC_MST_EMPLOYEE
INNER JOIN HETC_PAR_EMPLOYEE_TYPE
ON HETC_PAR_EMPLOYEE_TYPE.EMPLOYEE_TYPE_ID = HETC_MST_EMPLOYEE.EMPLOYEE_TYPE_ID
INNER JOIN HETC_MST_DOCTOR_SPECIALITY
ON HETC_MST_DOCTOR_SPECIALITY.DOCTOR_SPECIALITY_ID = HETC_MST_EMPLOYEE.DOCTOR_SPECIALITY_ID
INNER JOIN HETC_MST_DOCTOR_DEPARTMENT
ON HETC_MST_DOCTOR_DEPARTMENT.EMPLOYEE_ID = HETC_MST_EMPLOYEE.EMPLOYEE_ID
INNER JOIN HETC_MST_SUB_DEPARTMENT
ON HETC_MST_SUB_DEPARTMENT.SUB_DEPARTMENT_ID = HETC_MST_DOCTOR_DEPARTMENT.SUB_DEPARTMENT_ID
LEFT JOIN (SELECT DOCUMENT_PATH
FROM HETC_MST_DOCUMENT_PATH
INNER JOIN HETC_MST_TYPE_OF_ATTACHMENT
ON HETC_MST_DOCUMENT_PATH.TYPE_OF_DOCUMENT_ID = HETC_MST_TYPE_OF_ATTACHMENT.TYPE_OF_DOCUMENT_ID
WHERE HETC_MST_TYPE_OF_ATTACHMENT.TYPE_OF_DOCUMENT_CODE='DSI') AS DOC_SIGNATURE_PIC
ON 1=1
WHERE HETC_MST_SUB_DEPARTMENT.SUB_DEPARTMENT_ID = #subDepartmentId )a
declare #iterator int=1
declare #string varchar(max)= ''
declare #string2 varchar(max)= ''
declare #string3 varchar(max)= ''
declare #string4 varchar(max)= ''
declare #exec varchar(max)
while #iterator<=(select max(rownum) from #a)
begin
select #string2=
'['+cast(#iterator as varchar(max))+'].'+ 'EMPLOYEE_NAME'+
',['+cast(#iterator as varchar(max))+'].'+'EMPLOYEE_TYPE_NAME' +
',['+cast(#iterator as varchar(max))+'].'+'DOCTOR_SPECIALITY_DESCRIPTION' +
',['+cast(#iterator as varchar(max))+'].'+'SUB_DEPARTMENT_NAME' +
',['+cast(#iterator as varchar(max))+'].'+'DOCTOR_SIGNATURE'+
',['+cast(#iterator as varchar(max))+'].'+'DOCTOR_SIGNATURE_PIC'
from #a where rownum=#iterator
select #string= #string+#string2
select #string4=
case when #string4='' then
#string4+'['+cast(#iterator as varchar(max))+'].rownum='+cast(#iterator as varchar(max)) else
#string4+' and ['+cast(#iterator as varchar(max))+'].rownum='+cast(#iterator as varchar(max)) end
select #string3= case when #iterator>1 then #string3+' cross join #a ['+ cast(#iterator as varchar(max))+']' else '' end
set #iterator=#iterator+1
end
select #exec = 'select distinct'+ left(#string, len(#string)-1) +' from #a [1] '+#string3+ ' where '+ #string4
exec(''+#exec+'')
This isn't really an answer but a demonstration of how much using aliases can improve the legibility of your queries. Believe it or not this EXACTLY the same thing you posted. I just used aliases so you can read this instead of looking at a wall of text. The only actual change was to use a cross join instead of a left join on 1 = 1.
SELECT e.EMPLOYEE_NAME,
et.EMPLOYEE_TYPE_NAME,
s.DOCTOR_SPECIALITY_DESCRIPTION,
sd.SUB_DEPARTMENT_NAME,
e.DOCTOR_SIGNATURE,
CASE WHEN e.DOCTOR_SIGNATURE = ''
THEN ''
ELSE ISNULL(SIGNATURE_PATH.DOCUMENT_PATH, '') + e.DOCTOR_SIGNATURE
END AS DOCTOR_SIGNATURE_PIC
FROM HETC_MST_EMPLOYEE e
INNER JOIN HETC_PAR_EMPLOYEE_TYPE et ON et.EMPLOYEE_TYPE_ID = e.EMPLOYEE_TYPE_ID
INNER JOIN HETC_MST_DOCTOR_SPECIALITY s ON s.DOCTOR_SPECIALITY_ID = e.DOCTOR_SPECIALITY_ID
INNER JOIN HETC_MST_DOCTOR_DEPARTMENT dd ON dd.EMPLOYEE_ID = e.EMPLOYEE_ID
INNER JOIN HETC_MST_SUB_DEPARTMENT sd ON sd.SUB_DEPARTMENT_ID = dd.SUB_DEPARTMENT_ID
cross join
(
SELECT DOCUMENT_PATH
FROM HETC_MST_DOCUMENT_PATH p
INNER JOIN HETC_MST_TYPE_OF_ATTACHMENT a ON p.TYPE_OF_DOCUMENT_ID = a.TYPE_OF_DOCUMENT_ID
WHERE a.TYPE_OF_DOCUMENT_CODE='DSI'
) AS DOC_SIGNATURE_PIC
WHERE sd.SUB_DEPARTMENT_ID = #subDepartmentId
For the question at hand it is hard to tell what you are really wanting here. Maybe some conditional aggregation in combination with ROW_NUMBER. Or a PIVOT. You would need to post more details for this. Here is a great place to start. http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/

How to Check Parameter is not null in sql server?

I have a stored procedure. In this stored procedure I have to check that a particular parameter is not null. How can I do this? I wrote this:
ALTER PROCEDURE [dbo].[GetReelListings]
#locationUrlIdentifier VARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
declare #Sql varchar(max)=''
SET #Sql = 'SELECT CategoryName, CategoryUrlIdentifier, LocationUrlIdentifier, Directory.* FROM (SELECT ROW_NUMBER() OVER (PARTITION BY Category.Name ORDER BY CASE WHEN '''+ #locationUrlIdentifier + ''' = Location.UrlIdentifier THEN 1 ELSE CASE WHEN ''' + #locationUrlIdentifier + ''' IS NULL AND Directory.LocationId IS NULL THEN 0 ELSE 2 END END, Directory.SortOrder ) AS ''RowNo'', Category.Name AS CategoryName, Category.UrlIdentifier AS CategoryUrlIdentifier, dbo.Location.UrlIdentifier AS LocationUrlIdentifier, Directory.DirectoryId, CASE WHEN ''' + #locationUrlIdentifier + ''' = Location.UrlIdentifier THEN 1 ELSE CASE WHEN ''' + #locationUrlIdentifier + ''' IS NULL AND Directory.LocationId IS NULL THEN 0 ELSE 2 END END AS CategoryOrder FROM dbo.Directory INNER JOIN dbo.Category ON Directory.CategoryId = Category.CategoryId LEFT OUTER JOIN dbo.Location ON dbo.Directory.LocationId = location.Location_ID ) AS content INNER JOIN dbo.Directory ON content.DirectoryId = Directory.DirectoryId WHERE content.RowNo =1 '
if (#locationUrlIdentifier is null)
begin
SET #Sql = #Sql + ' and 1=1'
end
else
begin
SET #Sql = #Sql + ' and CategoryOrder = 1 '
end
print #SQl
EXECUTE (#Sql)
END
This will work in SQL but this will return a null Dataset in Codebehind.
Whenever you join strings and NULLs together, the result is NULL. By the time you're asking about whether the variable is NULL, you've already done this:
' + #locationUrlIdentifier + '
Several times. If it's NULL, so will #Sql be.
You might want to consider using COALESCE to replace the NULL with a suitable replacement (e.g. an empty string):
' + COALESCE(#locationUrlIdentifier,'') + '
You also still have a logic error on your final construction. If the variable is NULL, you'll have a where clause saying:
WHERE content.RowNo =1 1=1
Which isn't valid. I don't think you should be appending anything.
I'm also not clear on why you're doing this as dynamic SQL. The below seems to be an equivalent query which can be executed directly:
SELECT
CategoryName,
CategoryUrlIdentifier,
LocationUrlIdentifier,
Directory.*
FROM
(SELECT
ROW_NUMBER() OVER (
PARTITION BY Category.Name ORDER BY
CASE
WHEN #locationUrlIdentifier = Location.UrlIdentifier THEN 1
WHEN #locationUrlIdentifier IS NULL AND Directory.LocationId IS NULL THEN 0
ELSE 2
END,
Directory.SortOrder
) AS RowNo,
Category.Name AS CategoryName,
Category.UrlIdentifier AS CategoryUrlIdentifier,
dbo.Location.UrlIdentifier AS LocationUrlIdentifier,
Directory.DirectoryId,
CASE
WHEN #locationUrlIdentifier = Location.UrlIdentifier THEN 1
WHEN #locationUrlIdentifier IS NULL AND Directory.LocationId IS NULL THEN 0
ELSE 2
END AS CategoryOrder
FROM
dbo.Directory
INNER JOIN
dbo.Category
ON
Directory.CategoryId = Category.CategoryId
LEFT OUTER JOIN
dbo.Location
ON
dbo.Directory.LocationId = location.Location_ID
) AS content
INNER JOIN
dbo.Directory
ON
content.DirectoryId = Directory.DirectoryId
WHERE
content.RowNo =1 and
(#locationUrlIdentifier or CategoryOrder = 1)
You can do it just in ONE query:
Select Query ...where ...
and ((#locationUrlIdentifier is null) or (CategoryOrder = 1))
You can use NULLIF instead of IS NULL
Refer : Check if a parameter is null or empty in a stored procedure
http://msdn.microsoft.com/en-us/library/ms177562.aspx
Alternatively you can use ISNULL() check and then change the null to empty string
IF (ISNULL(#locationUrlIdentifier,'') = '')
OR even before this check you can use ISNULL() to convert from NULL to empty string if it persists to be a problem

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