;with cte as select * from customer
the select cte order by passing parameter
if(#orderby=1)
begin
select * from cte order by name
end
else if (#oderby=2)
begin
select * from cte order by applydate
end
else
begin
select * from cte order by customeramount
end
this following error invalid object cte How to Solve this sql query
I have to Solve The Problem
The code is
SELECT * FROM cte ORDER BY CASE #OrderBy WHEN 0 THEN Name ELSE null END , CASE #OrderBy WHEN 1 THEN Code ELSE null END ,CASE #OrderBy WHEN 2 THEN ApplyAmountTotal ELSE null END ,CASE #OrderBy WHEN 3 THEN ApplyDate ELSE null END
You can use case as below:
;With cte as
( select * from customer )
Select * from cte
Order by (case when #orderby=1 then [name]
when #orderby=2 then applydate
else customerAmount end )
I am find the Answer
SELECT * FROM cte ORDER BY CASE #OrderBy WHEN 0 THEN Name ELSE null END , CASE #OrderBy WHEN 1 THEN Code ELSE null END ,CASE #OrderBy WHEN 2 THEN ApplyAmountTotal ELSE null END ,CASE #OrderBy WHEN 3 THEN ApplyDate ELSE null END
name, applydate, customerAmount are not the same data type,
then you could use 3 CASE ...END clauses like this
SELECT *
FROM customer
ORDER BY
CASE
WHEN #oderby = 1 THEN name
ELSE ''
END,
CASE
WHEN #oderby = 2 THEN applydate
ELSE '1900-01-01'
END,
CASE
WHEN #oderby NOT IN (1,2) THEN customerAmount
ELSE 1
END
Related
I have a list of barcode and want to get the InvtID with Bookcode as a column. I want if there is no barcode exists then it will return 'no data' as well in the list. This is my current query but it only display the list of exist barcode only.
> WITH cte AS (SELECT *, ROW_NUMBER() OVER(PARTITION BY Barcode ORDER BY
InvtID Asc) rid FROM InvtCust WHERE Barcode In('123','9789830093697','9789830093727',)) SELECT InvtID,
BOOKCODE = coalesce(InvtID, 'Bookcode not found') FROM cte WHERE rid =
1 UNION SELECT InvtID = '', BOOKCODE = 'Bookcode not found' WHERE NOT
EXISTS(SELECT 1 FROM CTE)
I know there's a lot of question regarding this matter. But I really couldnt solve mine. I have tried these none of it working.
SELECT isnull((SELECT [InvtID]
FROM InvtCust WHERE Barcode IN('123','9789830093819')),'No bookcode found')
AS InvtID
Select case when s.InvtID IS NOT NULL Then s.InvtID else 'no data' end as Bookcode
from (Select InvtID as InvtID FROM InvtCust WHERE Barcode IN('123')) R
Left Join InvtCust s ON s.InvtID = R.InvtID
select expr1, InvtID from (
select *,ROW_NUMBER() over(order by isrealrow asc) rownum from (
select COUNT(*) as expr1, InvtID, 1 as isrealrow from [DANNY].[dbo].[InventoryCustomer]
where Barcode in ('ean','9789830093819','9789830093826','9789830094205')
Group by InvtID
union select 0,'No bookcode found',0 as isrealrow
)b
)c
where isrealrow=1 or rownum=1
IF NOT EXISTS (Select InvtID From InvtCust WHERE Barcode in ('123'))
Begin SELECT 'Bookcode not found' as Bookcode end
ELSE
SELECT InvtID From InvtCust WHERE Barcode in ('123')
In my view, it is better to put all your logic inside stored procedure:
CREATE PROCEDURE YourProcedure
AS
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
create table #Results
(
InvtID INT,
BookCode VARCHAR(255)
)
WITH cte AS (
SELECT
*
, ROW_NUMBER() OVER(PARTITION BY Barcode ORDER BY InvtID Asc) rid
FROM InvtCust
WHERE Barcode In('123','9789830093697','9789830093727'))
INSERT INTO #Results
(
InvtID,
BookCode
)
SELECT InvtID,
BOOKCODE = coalesce(InvtID, 'Bookcode not found')
FROM cte WHERE rid = 1
UNION
SELECT
InvtID = ''
, BOOKCODE = 'Bookcode not found'
WHERE NOT
EXISTS(SELECT 1 FROM CTE)
DECLARE #rows INT = 0;
SELECT #rows = COUNT(1) FROM #Results
SELECT #rows
IF #rows > 0
BEGIN
SELECT
*
#Results
END
ELSE
SELECT 'No Data'
GO
This query will give you the desired results. Am Assuming you have comma separated barcode list which you want to search in the table, If the query will find that barcode in the table it will return the barcode along with the InvtID else it will return the message 'no barcode found' for that record instead of InvtID .
For SQL server 2016 or Above
with BarcodeList as
(
select value as barcode
from string_split('aaaa,bbbb,cccc' , ',')
)
Select isnull(cast(InvtID as varchar), 'No barcode found') InvtID, b.Barcode From BarcodeList b left outer join InvtCust i
on b.barcode = i.barcode
Note: string_split function used in this query supported in SQL server 2016 onwards. If you are using SQL server below 2016 then you should create & use the custom split function as shown below.
For Below SQL server 2016
Custom Split Function
create FUNCTION [dbo].[String_Split]
(
#string NVARCHAR(MAX),
#delimiter CHAR(1)
)
RETURNS #output TABLE(value NVARCHAR(MAX)
)
BEGIN
DECLARE #start INT, #end INT
SELECT #start = 1, #end = CHARINDEX(#delimiter, #string)
WHILE #start < LEN(#string) + 1 BEGIN
IF #end = 0
SET #end = LEN(#string) + 1
INSERT INTO #output (value)
VALUES(SUBSTRING(#string, #start, #end - #start))
SET #start = #end + 1
SET #end = CHARINDEX(#delimiter, #string, #start)
END
RETURN
END
Go
Actual query
with BarcodeList as
(
select value as barcode
from dbo.[String_Split]('aaaa,bbbb,cccc' , ',')
)
Select isnull(cast(InvtID as varchar), 'No barcode found') InvtID, b.Barcode From BarcodeList b left outer join InvtCust i
on b.barcode = i.barcode
Why would this "Fail", if foo is less than 40 it should be "OK"
SELECT foo = '30', case when 'foo' >= '40' then 'Fail' else 'OK' end as 'Test'
So my actual query is (where ArrivalDate is a datetime):
SELECT Distinct [Title]
,DATEDIFF(day, [ArrivalDate], GetDate()) AS 'DaysOldSinceArrival'
,case when 'DaysOldSinceArrival' >= '40' then 'Fail' else 'OK' end as 'Test'
I believe the 'DaysOldSinceArrival' output must be a string and this is why the compare is not working. Is this failing for the same reason, if so, how do I make the 'DaysOldSinceArrival' an actual INT?
Your query is not correct, I feel you are trying to do something like following.
DECLARE #FOO INT
SET #FOO =30
SELECT #foo , case when #foo >= 40
then 'Fail' else 'OK' end as 'Test'
Output
(No column name) Test
30 OK
Issues in your query. You are comparing string 'foo' with a string
value '40', which is not ture.
EDIT
After looking your update, it seems you want to do like following
SELECT *,
(case when DaysOldSinceArrival >= 40 then 'Fail' else 'OK' end) as 'Test'
FROM
(
SELECT Distinct [Title]
,DATEDIFF(day, [ArrivalDate], GetDate()) AS 'DaysOldSinceArrival'
FROM [YOUR_TABLE]
) T
Yes, you are comparing a string to an INT which is implictly converted to a string and thus desn't equal your other string. You could use a CTE which can be more clear than a derrived table for some.
;with cte as(
SELECT
Distinct [Title]
,DaysOldSinceArrival = DATEDIFF(day, [ArrivalDate], GetDate()))
select
*
,Test = case when DaysOldSinceArrival >= 40 then 'Fail' else 'OK' end
from cte
I want to find if query does not return any results, then print 'no records found' else execute the query.
Here is my query,
select case when exists (
SELECT CAST(dm.[ID] AS VARCHAR(100)) as ID, case when dm.[Que_Type] = 0 then 'Valid' else 'Invalid' end [Type],
dm.[Name_List], t.[Name], dm.[FromDate], dm.[ToDate] FROM tblDays dm(nolock)
inner join (select pr.ID, pr.name from tblProduct pr(nolock)) as t
on dm.TradeID = t.ID where 1=1 and dm.ToDate between GETDATE() and DATEADD(dd, 15, GETDATE()))
then 'ok'
else 'no records'
end
In this query, I want to execute the query instead of printing 'ok'. How can I do that?
You could use an if statement along with exists
Since the conditional check is just to see if any records are returned, there is no need to select all those columns, so we just select 1. If records are found, the if tests true, and we'll run the sql statement. If no records are found, we'll drop to the else block and print 'no records'.
This may work for you:
IF(
exists(
select 1
FROM tblDays dm(nolock)
inner join (select pr.ID, pr.name from tblProduct pr(nolock)) as t
on dm.TradeID = t.ID
where 1=1
and dm.ToDate between GETDATE() and DATEADD(dd, 15, GETDATE())
)
)
BEGIN
SELECT CAST(dm.[ID] AS VARCHAR(100)) as ID
, case when dm.[Que_Type] = 0 then 'Valid' else 'Invalid' end [Type]
, dm.[Name_List]
, t.[Name]
, dm.[FromDate]
, dm.[ToDate]
FROM tblDays dm(nolock)
inner join (select pr.ID, pr.name from tblProduct pr(nolock)) as t
on dm.TradeID = t.ID
where 1=1
and dm.ToDate between GETDATE() and DATEADD(dd, 15, GETDATE())
END
ELSE
BEGIN
print 'no records'
END
You could use ##ROWCOUNT:
According to BOL:
Returns the number of rows affected by the last statement.
SELECT
CAST(dm.[ID] AS VARCHAR(100)) AS ID,
CASE WHEN dm.[Que_Type] = 0 THEN 'Valid' ELSE 'Invalid' END AS [Type],
dm.[Name_List],
t.[Name],
dm.[FromDate],
dm.[ToDate]
FROM tblDays dm(NOLOCK)
INNER JOIN (
SELECT
pr.ID,
pr.name
FROM tblProduct pr(NOLOCK)
) AS t
ON dm.TradeID = t.ID
WHERE
1 = 1
AND dm.ToDate BETWEEN GETDATE() AND DATEADD(dd, 15, GETDATE())
IF ##ROWCOUNT = 0
PRINT 'No records found.'
I have created a stored procedure where one case statement will be used 5 times, so is there any way to create a SQL variable so I can use that variable multiple times?
I have created a stored procedure where one case statement will be used 5 times, so is there any way to create a SQL variable so I can use that variable multiple times?
#Designation_Level1 varchar(100) = null ,
#pk_Designation_ID varchar(100) = null
AS
BEGIN
declare #JoiningDateChkforRule date=null
declare #MPHILDateChkforRule date=null
declare #caseVar varchar(max)
set #caseVar=''
SET #JoiningDateChkforRule = '1991-09-19 00:0:00.000'
SET #MPHILDateChkforRule = '1993-12-31 00:0:00.000'
set #Sql='SELECT Distinct SR.pk_employee_ID ,ISNULL(Last_Name,'''')+ '' ''+ISNULL(First_Name,'''')+'' ''+ISNULL(Middle_Name,'''') AS EmpName,Emp_Code,
TJoiningDateforRuleDesg.JoiningDateforRuleDesg,
-- if main designation and rule designation are same
--Main designation
CASE '+#pk_Designation_ID+'
WHEN ' +cast(#pk_Designation_IDForRule as varchar) +' THEN
--******************
CASE WHEN DATEDIFF(DAY, TJoiningDateforRuleDesg.JoiningDateforRuleDesg, '+cast(#JoiningDateChkforRule as varchar)+') > 0
THEN TJoiningDateforRuleDesg.JoiningDateforRuleDesg
ELSE
CASE WHEN DATEDIFF(day, isnull(NETSETQual.NETSETPassing_Date,MPHILQual.MPHILQualPassing_Date), isnull(MPHILQual.MPHILQualPassing_Date,NETSETQual.NETSETPassing_Date)) >= 0
THEN
CASE WHEN DATEDIFF(day, NETSETQual.NETSETPassing_Date, TJoiningDateforRuleDesg.JoiningDateforRuleDesg) <= 0
THEN NETSETQual.NETSETPassing_Date
ELSE
CASE WHEN NETSETQual.NETSETPassing_Date IS NULL
THEN
CASE WHEN DATEDIFF(DAY, MPHILQual.MPHILQualPassing_Date,'+CAST(#MPHILDateChkforRule as varchar) +')<= 0
THEN MPHILQual.MPHILQualPassing_Date
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
END
ELSE
CASE WHEN DATEDIFF(day, MPHILQual.MPHILQualPassing_Date, TJoiningDateforRuleDesg.JoiningDateforRuleDesg) <= 0
THEN
CASE WHEN DATEDIFF(DAY, MPHILQual.MPHILQualPassing_Date,'+CAST(#MPHILDateChkforRule as varchar) +') <= 0
THEN MPHILQual.MPHILQualPassing_Date
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
END
END
--******************
ELSE -- if main designation and rule designation are different
(Select min(Joining_Date) from HRMS_Employee_ServiceRecord (nolock)
where fk_Designation_ID in (SELECT * from dbo.Split('''+#pk_Designation_ID+''','',''))
and pk_Employee_ID = SR.pk_Employee_ID)
END as Senority_Joining_For_Order,
-- Level_1_Designation
CASE '+#Designation_Level1+'
WHEN '+cast(#pk_Designation_IDForRule as varchar) +' THEN
--******************
CASE WHEN DATEDIFF(DAY, TJoiningDateforRuleDesg.JoiningDateforRuleDesg, '+cast(#JoiningDateChkforRule as varchar)+') > 0
THEN TJoiningDateforRuleDesg.JoiningDateforRuleDesg
ELSE
CASE WHEN DATEDIFF(day, isnull(NETSETQual.NETSETPassing_Date,MPHILQual.MPHILQualPassing_Date), isnull(MPHILQual.MPHILQualPassing_Date,NETSETQual.NETSETPassing_Date)) >= 0
THEN
CASE WHEN DATEDIFF(day, NETSETQual.NETSETPassing_Date, TJoiningDateforRuleDesg.JoiningDateforRuleDesg) <= 0
THEN NETSETQual.NETSETPassing_Date
ELSE
CASE WHEN NETSETQual.NETSETPassing_Date IS NULL
THEN
CASE WHEN DATEDIFF(DAY, MPHILQual.MPHILQualPassing_Date,'+CAST(#MPHILDateChkforRule as varchar) +')<= 0
THEN MPHILQual.MPHILQualPassing_Date
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
END
ELSE
CASE WHEN DATEDIFF(day, MPHILQual.MPHILQualPassing_Date, TJoiningDateforRuleDesg.JoiningDateforRuleDesg) <= 0
THEN
CASE WHEN DATEDIFF(DAY, MPHILQual.MPHILQualPassing_Date,'+CAST(#MPHILDateChkforRule as varchar) +') <= 0
THEN MPHILQual.MPHILQualPassing_Date
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
END
END
--******************
ELSE
(Select min(Joining_Date) from HRMS_Employee_ServiceRecord (nolock)
where fk_Designation_ID in (SELECT * from dbo.Split('''+#Designation_Level1+''','',''))
and pk_Employee_ID = SR.pk_Employee_ID)
END as Level_1_Designation
FROM HRMS_EMPLOYEE_SERVICERECORD SR(NOLOCK)
INNER JOIN HRMS_Mst_Employee MstEmp (NOLOCK) ON SR.pk_Employee_ID=MstEmp.pk_Employee_ID AND Sr.IsCurrent_Appointment=''1'' AND Sr.fk_SeparationType_ID is null AND Sr.Is_Approved=''1''
INNER JOIN
(
Select pk_Employee_ID, min(Joining_Date) as JoiningDateforRuleDesg from HRMS_Employee_ServiceRecord (nolock)
where fk_Designation_ID = '+CAST(#pk_Designation_IDForRule as varchar)+'
group by pk_Employee_ID
)TJoiningDateforRuleDesg ON TJoiningDateforRuleDesg.pk_Employee_ID = SR.pk_Employee_ID
LEFT JOIN
(
Select Distinct RuleEQ.pk_Employee_ID as NETSETpk_Employee_ID, min(RuleEQ.Passing_Date) as NETSETPassing_Date
FROM HRMS_Employee_Qualifications RuleEQ
WHERE
fk_Course_ID in (SELECT * from dbo.Split('''+(#NETSETQualification)+''','',''))
group by RuleEQ.pk_Employee_ID
)NETSETQual ON
NETSETQual.NETSETpk_Employee_ID = SR.pk_Employee_ID
LEFT JOIN
(
Select Distinct RuleEQ.pk_Employee_ID as MPHILQualpk_Employee_ID, min(RuleEQ.Passing_Date) as MPHILQualPassing_Date
FROM HRMS_Employee_Qualifications RuleEQ
WHERE
fk_Course_ID in (SELECT * from dbo.Split('''+(#MPHILQualification)+''','',''))
group by RuleEQ.pk_Employee_ID
)MPHILQual ON
MPHILQual.MPHILQualpk_Employee_ID = SR.pk_Employee_ID
LEFT JOIN HRMS_Employee_Qualifications RuleEQ ON RuleEQ.pk_Employee_ID = SR.pk_employee_ID
where
MstEmp.deleted=''0'' and
SR.Appointment_Type in (''3'' , ''2'')
and SR.fk_SeparationType_ID is null and
SR.fk_Designation_ID='+ cast(#pk_Designation_IDForRule as varchar)+' AND
( (TJoiningDateforRuleDesg.JoiningDateforRuleDesg < '+cast(#JoiningDateChkforRule as varchar)+')
OR
(TJoiningDateforRuleDesg.JoiningDateforRuleDesg >= '+cast(#JoiningDateChkforRule as varchar)+' AND RuleEQ.fk_Course_ID IN (SELECT * from dbo.Split('''+#NETSETQualification+''','','')))
OR
(TJoiningDateforRuleDesg.JoiningDateforRuleDesg >= '+cast(#JoiningDateChkforRule as varchar)+' AND RuleEQ.fk_Course_ID IN (SELECT * from dbo.Split('''+#MPHILQualification+''','','')) ) ) '
-- and ES.pk_CourseBranch_ID in (35)
end
No, you can't put it into a variable, unless you'll be using dynamic SQL all over.
Depending on what the code actually look like, you can use a view (or a function) or a CTE to encapsulate the part of it.
I'd rather stay with writing it five times, and expect the better performace.
I have created a stored procedure where one case statement will be used 5 times, so is there any way to create a SQL variable so I can use that variable multiple times?
I have created a stored procedure where one case statement will be used 5 times, so is there any way to create a SQL variable so I can use that variable multiple times?
#Designation_Level1 varchar(100) = null ,
#pk_Designation_ID varchar(100) = null
AS
BEGIN
declare #JoiningDateChkforRule date=null
declare #MPHILDateChkforRule date=null
declare #caseVar varchar(max)
set #caseVar=''
SET #JoiningDateChkforRule = '1991-09-19 00:0:00.000'
SET #MPHILDateChkforRule = '1993-12-31 00:0:00.000'
set #Sql='SELECT Distinct SR.pk_employee_ID ,ISNULL(Last_Name,'''')+ '' ''+ISNULL(First_Name,'''')+'' ''+ISNULL(Middle_Name,'''') AS EmpName,Emp_Code,
TJoiningDateforRuleDesg.JoiningDateforRuleDesg,
-- if main designation and rule designation are same
--Main designation
CASE '+#pk_Designation_ID+'
WHEN ' +cast(#pk_Designation_IDForRule as varchar) +' THEN
--******************
CASE WHEN DATEDIFF(DAY, TJoiningDateforRuleDesg.JoiningDateforRuleDesg, '+cast(#JoiningDateChkforRule as varchar)+') > 0
THEN TJoiningDateforRuleDesg.JoiningDateforRuleDesg
ELSE
CASE WHEN DATEDIFF(day, isnull(NETSETQual.NETSETPassing_Date,MPHILQual.MPHILQualPassing_Date), isnull(MPHILQual.MPHILQualPassing_Date,NETSETQual.NETSETPassing_Date)) >= 0
THEN
CASE WHEN DATEDIFF(day, NETSETQual.NETSETPassing_Date, TJoiningDateforRuleDesg.JoiningDateforRuleDesg) <= 0
THEN NETSETQual.NETSETPassing_Date
ELSE
CASE WHEN NETSETQual.NETSETPassing_Date IS NULL
THEN
CASE WHEN DATEDIFF(DAY, MPHILQual.MPHILQualPassing_Date,'+CAST(#MPHILDateChkforRule as varchar) +')<= 0
THEN MPHILQual.MPHILQualPassing_Date
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
END
ELSE
CASE WHEN DATEDIFF(day, MPHILQual.MPHILQualPassing_Date, TJoiningDateforRuleDesg.JoiningDateforRuleDesg) <= 0
THEN
CASE WHEN DATEDIFF(DAY, MPHILQual.MPHILQualPassing_Date,'+CAST(#MPHILDateChkforRule as varchar) +') <= 0
THEN MPHILQual.MPHILQualPassing_Date
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
END
END
--******************
ELSE -- if main designation and rule designation are different
(Select min(Joining_Date) from HRMS_Employee_ServiceRecord (nolock)
where fk_Designation_ID in (SELECT * from dbo.Split('''+#pk_Designation_ID+''','',''))
and pk_Employee_ID = SR.pk_Employee_ID)
END as Senority_Joining_For_Order,
-- Level_1_Designation
CASE '+#Designation_Level1+'
WHEN '+cast(#pk_Designation_IDForRule as varchar) +' THEN
--******************
CASE WHEN DATEDIFF(DAY, TJoiningDateforRuleDesg.JoiningDateforRuleDesg, '+cast(#JoiningDateChkforRule as varchar)+') > 0
THEN TJoiningDateforRuleDesg.JoiningDateforRuleDesg
ELSE
CASE WHEN DATEDIFF(day, isnull(NETSETQual.NETSETPassing_Date,MPHILQual.MPHILQualPassing_Date), isnull(MPHILQual.MPHILQualPassing_Date,NETSETQual.NETSETPassing_Date)) >= 0
THEN
CASE WHEN DATEDIFF(day, NETSETQual.NETSETPassing_Date, TJoiningDateforRuleDesg.JoiningDateforRuleDesg) <= 0
THEN NETSETQual.NETSETPassing_Date
ELSE
CASE WHEN NETSETQual.NETSETPassing_Date IS NULL
THEN
CASE WHEN DATEDIFF(DAY, MPHILQual.MPHILQualPassing_Date,'+CAST(#MPHILDateChkforRule as varchar) +')<= 0
THEN MPHILQual.MPHILQualPassing_Date
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
END
ELSE
CASE WHEN DATEDIFF(day, MPHILQual.MPHILQualPassing_Date, TJoiningDateforRuleDesg.JoiningDateforRuleDesg) <= 0
THEN
CASE WHEN DATEDIFF(DAY, MPHILQual.MPHILQualPassing_Date,'+CAST(#MPHILDateChkforRule as varchar) +') <= 0
THEN MPHILQual.MPHILQualPassing_Date
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
ELSE TJoiningDateforRuleDesg.JoiningDateforRuleDesg
END
END
END
--******************
ELSE
(Select min(Joining_Date) from HRMS_Employee_ServiceRecord (nolock)
where fk_Designation_ID in (SELECT * from dbo.Split('''+#Designation_Level1+''','',''))
and pk_Employee_ID = SR.pk_Employee_ID)
END as Level_1_Designation
FROM HRMS_EMPLOYEE_SERVICERECORD SR(NOLOCK)
INNER JOIN HRMS_Mst_Employee MstEmp (NOLOCK) ON SR.pk_Employee_ID=MstEmp.pk_Employee_ID AND Sr.IsCurrent_Appointment=''1'' AND Sr.fk_SeparationType_ID is null AND Sr.Is_Approved=''1''
INNER JOIN
(
Select pk_Employee_ID, min(Joining_Date) as JoiningDateforRuleDesg from HRMS_Employee_ServiceRecord (nolock)
where fk_Designation_ID = '+CAST(#pk_Designation_IDForRule as varchar)+'
group by pk_Employee_ID
)TJoiningDateforRuleDesg ON TJoiningDateforRuleDesg.pk_Employee_ID = SR.pk_Employee_ID
LEFT JOIN
(
Select Distinct RuleEQ.pk_Employee_ID as NETSETpk_Employee_ID, min(RuleEQ.Passing_Date) as NETSETPassing_Date
FROM HRMS_Employee_Qualifications RuleEQ
WHERE
fk_Course_ID in (SELECT * from dbo.Split('''+(#NETSETQualification)+''','',''))
group by RuleEQ.pk_Employee_ID
)NETSETQual ON
NETSETQual.NETSETpk_Employee_ID = SR.pk_Employee_ID
LEFT JOIN
(
Select Distinct RuleEQ.pk_Employee_ID as MPHILQualpk_Employee_ID, min(RuleEQ.Passing_Date) as MPHILQualPassing_Date
FROM HRMS_Employee_Qualifications RuleEQ
WHERE
fk_Course_ID in (SELECT * from dbo.Split('''+(#MPHILQualification)+''','',''))
group by RuleEQ.pk_Employee_ID
)MPHILQual ON
MPHILQual.MPHILQualpk_Employee_ID = SR.pk_Employee_ID
LEFT JOIN HRMS_Employee_Qualifications RuleEQ ON RuleEQ.pk_Employee_ID = SR.pk_employee_ID
where
MstEmp.deleted=''0'' and
SR.Appointment_Type in (''3'' , ''2'')
and SR.fk_SeparationType_ID is null and
SR.fk_Designation_ID='+ cast(#pk_Designation_IDForRule as varchar)+' AND
( (TJoiningDateforRuleDesg.JoiningDateforRuleDesg < '+cast(#JoiningDateChkforRule as varchar)+')
OR
(TJoiningDateforRuleDesg.JoiningDateforRuleDesg >= '+cast(#JoiningDateChkforRule as varchar)+' AND RuleEQ.fk_Course_ID IN (SELECT * from dbo.Split('''+#NETSETQualification+''','','')))
OR
(TJoiningDateforRuleDesg.JoiningDateforRuleDesg >= '+cast(#JoiningDateChkforRule as varchar)+' AND RuleEQ.fk_Course_ID IN (SELECT * from dbo.Split('''+#MPHILQualification+''','','')) ) ) '
-- and ES.pk_CourseBranch_ID in (35)
end
No, you can't put it into a variable, unless you'll be using dynamic SQL all over.
Depending on what the code actually look like, you can use a view (or a function) or a CTE to encapsulate the part of it.
I'd rather stay with writing it five times, and expect the better performace.