dynamic Procedure, remove last string chars - sql

I have a parameter that dynamically generates UNION ALL
depends on the input.
SELECT #CMD +=N'
SET NOCOUNT ON;
SELECT
COUNT(CASE WHEN RFRD.QueuTypeID=4
THEN RFRD.QueuTypeID
END) RequiredaQueue
,COUNT(DISTINCT RFRD.LeadDocumentID) AS Repeat,CONCAT('''+RF+''' ,'' '') AS RiskFactorID
FROM FCT.RiskMng_fact_RiskFactorResultDetails AS RFRD
UNION ALL
SELECT
COUNT(CASE WHEN RFRD.QueuTypeID=4
THEN RFRD.QueuTypeID
END) RequiredaQueue
,COUNT(DISTINCT RFRD.LeadDocumentID)AS Repeat,CONCAT('''+RF+''' ,''*'') AS RiskFactorID
FROM FCT.RiskMng_fact_RiskFactorResultDetails AS RFRD'
--------------
FROM #cte RF
EXEC sys.sp_executesql #CMD
at the end i want to connect them all into one long UNION, so i added a UNION ALL in the end:
SELECT #CMD +=N'
SET NOCOUNT ON;
SELECT
COUNT(CASE WHEN RFRD.QueuTypeID=4
THEN RFRD.QueuTypeID
END) RequiredaQueue
,COUNT(DISTINCT RFRD.LeadDocumentID) AS Repeat,CONCAT('''+RF+''' ,'' '') AS RiskFactorID
FROM FCT.RiskMng_fact_RiskFactorResultDetails AS RFRD
UNION ALL
SELECT
COUNT(CASE WHEN RFRD.QueuTypeID=4
THEN RFRD.QueuTypeID
END) RequiredaQueue
,COUNT(DISTINCT RFRD.LeadDocumentID)AS Repeat,CONCAT('''+RF+''' ,''*'') AS RiskFactorID
FROM FCT.RiskMng_fact_RiskFactorResultDetails AS RFRD'
--------------
+' UNION ALL ' <-----------------------
FROM #cte RF
EXEC sys.sp_executesql #CMD
after it runs, the last UNION ALL is Needless,
and i get errors:
ON OU.ID = RFRD.Entity_OrganizationUnitID
INNER JOIN #Entity_OrganizationUnitTypeIDs OUT
ON OUT.ID = RFRD.Entity_OrganizationUnitTypeID
WHERE RFRD.EntityTypeID = 1055
and RFRD.riskfactorid IN(6249,6102)
AND RFRD1.ID IS NULL
UNION ALL
Msg 156, Level 15, State 1, Line 118
can anyone suggest how can i remove only the last UNION ALL?
maybe i should not add a UNION AL at the end?
Thanks

At the end you need to remove it by
set #CMD = substring(#CMD,1,len(#CMD)-9)
EXEC sys.sp_executesql #CMD

The UNION ALL command takes two parameters, the table before and the table after the UNION ALL command.
So it should allways have the form
SELECT col1,col2 FROM A
UNION ALL
SELECT col3 as col1,col4 as col2 FROM B

When you are concatenating your SELECT statements, why not check to see if the existing string is empty, and add the UNION ALL then only if it is required, for example:
SELECT #CMD = #CMD +
CASE WHEN #CMD = '' THEN '' ELSE ' UNION ALL ' END +
'SELECT ... '
Then you won't be in the situation where you'll have to strip anything back out again.

Related

Add column name to a variable and use it in later calculation in WHERE clause

I have a problem. I need to determine the name of the column under which the calculations will continue. So I wrote a select:
DECLARE #column VARCHAR(MAX)
DECLARE #ColumnA VARCHAR(MAX)
DECLARE #ColumnB VARCHAR(MAX)
SET #ColumnA = 'RegistrationDate'
SET #ColumnB = 'EntryDate'
SET #column = CASE
WHEN CONVERT(DATE,GETDATE()) NOT IN (
'2021-08-04','2021-08-05','2021-08-06','2021-08-07','2021-08-08','2021-08-09','2021-08-10','2021-09-07','2021-09-08','2021-09-09','2021-09-10','2021-09-11',
'2021-09-12','2021-09-13','2021-10-05','2021-10-06','2021-10-07','2021-10-08','2021-10-09','2021-10-10','2021-10-11','2021-11-09','2021-11-10','2021-11-11','2021-11-12','2021-11-13','2021-11-14','2021-11-15','2021-12-07',
'2021-12-08','2021-12-09','2021-12-10','2021-12-11','2021-12-12','2021-12-13'
) THEN
QUOTENAME(#Column)
ELSE
QUOTENAME(#ColumnB)
END
SELECT #column
which returns me [RegistrationDate] or [EntryDate] and stores this in variable #column. Now, when I know under which column should I calculate, I want to insert this variable #column in to my main select one of the WHERE clause:
DECLARE #column VARCHAR(MAX)
DECLARE #ColumnA VARCHAR(MAX)
DECLARE #ColumnB VARCHAR(MAX)
SET #ColumnA = 'RegistrationDate'
SET #ColumnB = 'EntryDate'
SET #column = CASE
WHEN CONVERT(DATE,GETDATE()) NOT IN (
'2021-08-04','2021-08-05','2021-08-06','2021-08-07','2021-08-08','2021-08-09','2021-08-10','2021-09-07','2021-09-08','2021-09-09','2021-09-10','2021-09-11',
'2021-09-12','2021-09-13','2021-10-05','2021-10-06','2021-10-07','2021-10-08','2021-10-09','2021-10-10','2021-10-11','2021-11-09','2021-11-10','2021-11-11','2021-11-12','2021-11-13','2021-11-14','2021-11-15','2021-12-07',
'2021-12-08','2021-12-09','2021-12-10','2021-12-11','2021-12-12','2021-12-13'
) THEN
QUOTENAME(#Column)
ELSE
QUOTENAME(#ColumnB)
END
SELECT
CASE WHEN final.Branch IS NULL THEN 'Total'
ELSE final.Branch
END AS 'Branch',
final.TR
FROM
(
SELECT
CASE
WHEN main.BRANCHNO = 1 THEN 'One'
WHEN main.BRANCHNO = 2 THEN 'Two'
WHEN main.BRANCHNO = 3 THEN 'Three'
WHEN main.BRANCHNO = 4 THEN 'Four'
WHEN main.BRANCHNO = 5 THEN 'Five'
WHEN main.BRANCHNO = 6 THEN 'Six'
END AS 'Branch',
COUNT(*) AS 'TR'
FROM
(
SELECT
*
FROM
[TABLE]
WHERE
Status = 100
AND
BRANCHNO IN (1,2,3,4,5,6)
AND
Type = 'TR'
AND
**#column** = CONVERT(DATE, CASE WHEN DATENAME(dw, getdate()) = 'Monday' THEN getdate()-3 ELSE getdate()-1 END
)
) AS main
GROUP BY
main.BRANCHNO WITH ROLLUP
) AS final
But when I execute query it returns me an error:
Msg 241, Level 16, State 1, Line 11 Conversion failed when converting
date and/or time from character string.
I imagined everything very simple: I put a column name into a variable, and then, that name placed at the beginning of the WHERE clause will be recognized as the column name and then *= CONVERT(DATE, CASE WHEN DATENAME(dw, getdate()) etc will do all work.
But that did not happen. Maybe someone knows why and maybe they know how to solve this task?
You can't use a variable to reference a column name. #column is just a piece of data, which just so happens to contain a column name as a string, but it's still just a string, not actually a reference to a column in a table.
Some options you have seem to be...
AND CASE #column WHEN 'RegistrationDate' THEN RegistrationDate
WHEN 'EntryDate' THEN EntryDate
END
=
CONVERT(DATE, CASE WHEN DATENAME(dw, getdate()) = 'Monday' THEN getdate()-3 ELSE getdate()-1 END)
Or, have two queries which only differ in the column being referenced...
IF (#column = 'RegistrationDate')
<query1>
ELSE IF (#column = 'EntryDate')
<query2>
Or "Dynamic SQL" where you build up a new string with your SQL code and execute that by call sp_executesql (assuming this is SQL Server, which it appears to be).
I recommend reading this : https://www.sommarskog.se/dyn-search.html
EDIT: A pure SQL alternative, assuming SQL Server
DECLARE #mode INT = CASE
WHEN CONVERT(DATE,GETDATE()) NOT IN (
'2021-08-04','2021-08-05','2021-08-06','2021-08-07','2021-08-08','2021-08-09','2021-08-10','2021-09-07','2021-09-08','2021-09-09','2021-09-10','2021-09-11',
'2021-09-12','2021-09-13','2021-10-05','2021-10-06','2021-10-07','2021-10-08','2021-10-09','2021-10-10','2021-10-11','2021-11-09','2021-11-10','2021-11-11','2021-11-12','2021-11-13','2021-11-14','2021-11-15','2021-12-07',
'2021-12-08','2021-12-09','2021-12-10','2021-12-11','2021-12-12','2021-12-13'
) THEN
0
ELSE
1
END;
DECLARE #filter_date DATE = CONVERT(DATE, CASE WHEN DATENAME(dw, getdate()) = 'Monday' THEN getdate()-3 ELSE getdate()-1 END;
WITH
source AS
(
SELECT
*
FROM
[TABLE]
WHERE
Status = 100
AND BRANCHNO IN (1,2,3,4,5,6)
AND Type = 'TR'
),
filtered_source AS
(
SELECT 0 AS mode, * FROM source WHERE RegistrationDate = #filter_date
UNION ALL
SELECT 1 AS mode, * FROM source WHERE EntryDate = #filter_date
)
SELECT
COALESCE(
CASE
WHEN BRANCHNO = 1 THEN 'One'
WHEN BRANCHNO = 2 THEN 'Two'
WHEN BRANCHNO = 3 THEN 'Three'
WHEN BRANCHNO = 4 THEN 'Four'
WHEN BRANCHNO = 5 THEN 'Five'
WHEN BRANCHNO = 6 THEN 'Six'
END,
'Total'
)
AS 'Branch',
COUNT(*) AS 'TR'
FROM
filtered_source
WHERE
mode = #mode
GROUP BY
GROUPING SETS (
(mode),
(mode, BRANCHNO)
);
By always including mode in the GROUPING SETS, the optimiser might be able to yield a better execution plan for the two scenarios.
Still read the link given above though, at the very least to understand why this is necessary, or perhaps why it doesn't quite manage to yield the best execution plan.

How to create stored procedure with view?

I tried to execute this code and it worked o.k without the the stored procedure and with it, it made an error.
The error is:
Msg 102, Level 15, State 1, Procedure UV_MTBF, Line 251
Incorrect syntax near 'Event_'.
Is the stored procedure have a limitation in length?
can someone help me with my code?
edit*
my problem is with ' + QUOTENAME(#category,N'''') + N'
i want to add an integer from a variable that i received in the stored procedure. how can i do it?
enter code here:
CREATE PROCEDURE dbo.MTBFCalculation #Category int, #Action bit, #relateToParent bit
as
IF EXISTS (SELECT 1 FROM sys.objects WHERE [name] = '[dbo].[UV_MTBF]')
DROP VIEW [dbo].[UV_MTBF];
DECLARE #Event nvarchar(MAX) = N'
CREATE VIEW [dbo].[UV_MTBF]
as
with failureReportTable as (SELECT [ID] as failure_id
,[Login_ID]
,[Event_ID]
,[StartDate]
,[EndDate]
,DATEDIFF(Hour,[StartDate],[EndDate]) as eventDurationMin
,[IsRelevantForBI]
,[IsParallelReport]
,[ParentReportID]
,[IsPausedEvent]
,Case
When ParentReportID>0 Then 1 --Chiled
When IsParallelReport=1 Then 2 --Parent
Else 3 --not Parallel
End as ParallelStatus
FROM [TDM_Analysis].[dbo].[FailureReports]),
fullFailure as (select *, ROW_NUMBER() OVER (ORDER BY [StartDate] ) AS IDrow
from failureReportTable join [TDM_Analysis].[dbo].[UV_filteredLogins] as viewLogins on failureReportTable.Login_ID=viewLogins.ID
WHERE event_id IN (SELECT ID FROM [TDM_Analysis].[dbo].[Events] where EventCategory_ID=' + QUOTENAME(#category,N'''') + N')
and (ParallelStatus=3 or ParallelStatus=(case when ' + QUOTENAME(#relateToParent,N'''') + N'=1 then 2 else 1 end))),
--------------create first failure table------------------
failure_Event_1 as (select f1.failure_id as Event_1_Failure_ID
,f1.[Login_ID] as Event_1_Login_ID
,f1.[Event_ID] as Event_1_Event_ID
,f1.[StartDate] as Event_1_StartDate
,f1.[EndDate] as Event_1_EndDate
,f1.eventDurationMin as Event_1_eventDurationMin
--,f1.[IsRelevantForBI] as Event_1_IsRelevantForBI
--,f1.[IsParallelReport] as Event_1_IsParallelReport
-- ,f1.[ParentReportID] as Event_1_ParentReportID
-- ,f1.[IsPausedEvent] as Event_1_IsPausedEvent
,f1.[Test_Name] as Event_1_TestName
,f1.Phase_Name as Event_1_PhaseName
,f1.PressName as Event_1_PressName
,f1.PressType as Event_1_PressType
--,f1.[Operator] as Event_1_Operator
,f1.[LoginDate] as Event_1_LoginDate
,f1.[LogoutDate] as Event_1_LogoutDate
,f1.TimeDiff as Event_1_LoginDuration
,f1.IDrow+1 as row1
from fullFailure as f1),
--------------create second failure table------------------
failure_Event_2 as (select f1.failure_id as Event_2_Failure_ID
,f1.[Login_ID] as Event_2_Login_ID
,f1.[Event_ID] as Event_2_Event_ID
,f1.[StartDate] as Event_2_StartDate
,f1.[EndDate] as Event_2_EndDate
,f1.eventDurationMin as Event_2_eventDurationMin
-- ,f1.[IsRelevantForBI] as Event_2_IsRelevantForBI
-- ,f1.[IsParallelReport] as Event_2_IsParallelReport
-- ,f1.[ParentReportID] as Event_2_ParentReportID
-- ,f1.[IsPausedEvent] as Event_2_IsPausedEvent
,f1.[Test_Name] as Event_2_TestName
,f1.Phase_Name as Event_2_PhaseName
,f1.PressName as Event_2_PressName
,f1.PressType as Event_2_PressType
-- ,f1.[Operator] as Event_2_Operator
,f1.[LoginDate] as Event_2_LoginDate
,f1.[LogoutDate] as Event_2_LogoutDate
,f1.TimeDiff as Event_2_LoginDuration
,f1.IDrow as row2
from fullFailure as f1),
------------- join two failure tabels and calculating MTTR-mean time to repair (duration of failue), MTTF-mean time to failue( end of one until start of a new one), MTBF-mean time between failue (from start of a failure to start of a new one)--------------------
joinFailures as (select *, Event_1_eventDurationMin as MTTR
,CASE
When isnull(f2.row2,0)=0 then DATEDIFF(HOUR,f1.Event_1_EndDate,f1.Event_1_LogoutDate)
WHEN f1.Event_1_Login_ID=f2.Event_2_Login_ID THEN DATEDIFF(HOUR,f1.Event_1_EndDate,f2.Event_2_StartDate)
When (select TOP 1 sum(timediff)
from [TDM_Analysis].[dbo].[UV_filteredLogins]
where logindate>f1.Event_1_LogoutDate and logindate<f2.Event_2_LoginDate) is null then DATEDIFF(HOUR,f1.Event_1_EndDate,f1.Event_1_LogoutDate)+DATEDIFF(HOUR,f2.Event_2_LoginDate, f2.Event_2_StartDate)
ELSE
(select TOP 1 sum(timediff)+DATEDIFF(HOUR,f1.Event_1_EndDate,f1.Event_1_LogoutDate)+DATEDIFF(HOUR,f2.Event_2_LoginDate, f2.Event_2_StartDate)
from [TDM_Analysis].[dbo].[UV_filteredLogins]
where logindate>f1.Event_1_LogoutDate and logindate<f2.Event_2_LoginDate)
END AS MTTF
from failure_Event_1 as f1 left join failure_Event_2 as f2 on f1.row1=f2.row2),
positiveJoinFailure as (select * from joinFailures where MTTF>=0)
---- select calculation table order by ascending time----------
select * --Event_1_Failure_ID,Event_2_Failure_ID,MTTR,MTTF, MTTR+MTTF as MTFB
from positiveJoinFailure
--order by row1
';
--------------------------------------------------------Action------------------------------------------------------------------------------
if #Action=1
begin
EXEC sp_executesql #Event;
end
for this part of your query
where EventCategory_ID=' + QUOTENAME(#category,N'''') + N')
2 option here, you convert the value of #category to string and then concatenate with the dynamic query
where EventCategory_ID=' + convert(varchar(10), #category)
OR, you pass the value in as a parameter.
for this option, you specify #category in the dynamic query
where EventCategory_ID= #category
and (ParallelStatus=3 ....
and you pass the value in at sp_executesql
EXEC sp_executesql #Event, N'#category int', #category
By the way, Option 2 is the preferred method when using dynamic query

SQL Server : IF condition not working in stored procedure

I have this condition in my stored procedure to determine which WHERE clause to use:
IF (#communityDesc = 'All Areas')
BEGIN
WHERE V_CONSTAT_ACTUAL_DATES.AREA_DESC IN (SELECT name
FROM dbo.splitstring(#communityDesc))
AND V_CONSTAT_ACTUAL_DATES.DATE_TO_END >= GETDATE()
END
ELSE
BEGIN
WHERE V_CONSTAT_ACTUAL_DATES.DATE_TO_END >= GETDATE()
END
ORDER BY V_CONSTAT_ACTUAL_DATES.DATE_TO_END
but I get a long list of errors:
Msg 156, Level 15, State 1, Procedure GetProductionSchedule, Line 256
Incorrect syntax near the keyword 'WHERE'.
Msg 156, Level 15, State 1, Procedure GetProductionSchedule, Line 256
Incorrect syntax near the keyword 'AND'.
What am I doing wrong?
You can't separate out a query by a conditional. You'd have to do something like.
if(#communityDesc = 'All Areas')
BEGIN
SELECT * FROM Table
WHERE V_CONSTAT_ACTUAL_DATES.AREA_DESC IN
(select name from dbo.splitstring(#communityDesc))
AND V_CONSTAT_ACTUAL_DATES.DATE_TO_END>=GETDATE()
ORDER BY V_CONSTAT_ACTUAL_DATES.DATE_TO_END
END
else
BEGIN
SELECT * FROM Table
WHERE V_CONSTAT_ACTUAL_DATES.DATE_TO_END>=GETDATE()
ORDER BY V_CONSTAT_ACTUAL_DATES.DATE_TO_END
END
Your other option would be to conditionally build the query:
DECLARE #Query VARCHAR(1000)
SET #Query = 'SELECT * FROM TABLE '
if(#communityDesc = 'All Areas')
BEGIN
SET #Query = #Query +
'WHERE V_CONSTAT_ACTUAL_DATES.AREA_DESC IN (select name from dbo.splitstring(#communityDesc)) AND V_CONSTAT_ACTUAL_DATES.DATE_TO_END>=GETDATE() '
END
ELSE
SET #Query = #Query +
'WHERE V_CONSTAT_ACTUAL_DATES.DATE_TO_END>=GETDATE() '
BEGIN
SET #Query = #Query + 'ORDER BY V_CONSTAT_ACTUAL_DATES.DATE_TO_END'
END
exec sp_executesql #Query
Or just put all of the logic into a single WHERE
SELECT *
FROM [Table]
WHERE V_CONSTAT_ACTUAL_DATES.DATE_TO_END >= GETDATE()
AND (#communityDesc = 'All Areas'
OR V_CONSTAT_ACTUAL_DATES.AREA_DESC IN (SELECT name
FROM dbo.splitstring(#communityDesc)))
Im not sure you have your logic right.. You probably want to split #communityDesc if it's not equal to All Areas I've updated my answer to reflect what I mean.
You should probably write it like this
-- your preceding select statements followed by this line
SELECT * FROM V_CONSTAT_ACTUAL_DATES
WHERE
(
#communityDesc = 'All Areas' AND
V_CONSTAT_ACTUAL_DATES.AREA_DESC IN (select name from dbo.splitstring(#communityDesc)) AND
V_CONSTAT_ACTUAL_DATES.DATE_TO_END>=GETDATE()
)
OR
( #communityDesc <> 'All Areas' AND V_CONSTAT_ACTUAL_DATES.DATE_TO_END>=GETDATE()
)
ORDER BY V_CONSTAT_ACTUAL_DATES.DATE_TO_END
This can also be simplified as
-- your preceding select statements followed by this line
SELECT * FROM V_CONSTAT_ACTUAL_DATES
WHERE
V_CONSTAT_ACTUAL_DATES.DATE_TO_END>=GETDATE()
AND NOT
(
#communityDesc <> 'All Areas' OR
V_CONSTAT_ACTUAL_DATES.AREA_DESC not IN (select name from dbo.splitstring(#communityDesc))
)
ORDER BY V_CONSTAT_ACTUAL_DATES.DATE_TO_END
which can be further optimized like below
-- your preceding select statements followed by this line
SELECT * FROM V_CONSTAT_ACTUAL_DATES
LEFT JOIN (select name from dbo.splitstring(#communityDesc) Temp
ON Temp.name=V_CONSTAT_ACTUAL_DATES.AREA_DESC
WHERE
V_CONSTAT_ACTUAL_DATES.DATE_TO_END>=GETDATE()
AND NOT
(
#communityDesc <> 'All Areas' OR Temp.Name is null
)
)
ORDER BY V_CONSTAT_ACTUAL_DATES.DATE_TO_END

Where clause concat with comma

I am trying to write what I thought would be a simple where clause. The FULLNAME string is formatted like this ("Doe, John"), hence the where clause and concat function.
Here is the query:
SELECT *
FROM table
WHERE concat(LAST_NM, ', ', FIRST_NM) = FULLNAME;
The query fails with the following error:
Error Executing Database Query. [Macromedia][SQLServer JDBC Driver]
[SQLServer]Incorrect syntax near ','.
Is your FullName something like "Doe, John"?
Is your FullName complete?
if not
SELECT *
FROM table
WHERE concat(LAST_NM, ', ', FIRST_NM) like ('%' + FULLNAME + '%')
Although I do not see anything wrong with your query, I would like to suggest a way to troubleshoot, by trying to find if it is a specific raw values that cause the concat function to break.
The idea is to iterate through the raws printing each one's values so you'll know which one (if at all) fails it, and it might be easier to take it from there to the next step.
--Copy your table data to a temporary table
--E.g.
SELECT *
into #table
FROM
(
select 'Doe' as LAST_NM , 'Jhon' as FIRST_NM
union
select 'Ryan' as LAST_NM , 'Jack' as FIRST_NM
union
select 'Dylan' as LAST_NM , 'Bob' as FIRST_NM
) a
--Iterate through the rows to see which one causes the issue
DECLARE #I INT = 1
DECLARE #TableCount INT = (select count(*) from #table)
DECLARE #FN varchar(100)
DECLARE #LN varchar(100)
WHILE #I <= #TableCount
BEGIN
SET #FN = (select Top 1 FIRST_NM from #table)
SET #LN = (select Top 1 LAST_NM from #table)
print(#I)
print(#FN)
print(#LN)
print('------------------')
delete top (1) from #table
SET #I = #I + 1
END

Select with IN and Like

I have a very interesting problem. I have an SSRS report with a multiple select drop down.
The drop down allows to select more than one value, or all values.
All values is not the problem.
The problem is 1 or the combination of more than 1 option
When I select in the drop down 'AAA' it should return 3 values: 'AAA','AAA 1','AAA 2'
Right now is only returning 1 value.
QUESTION:
How can make the IN statement work like a LIKE?
The Drop down select
SELECT '(All)' AS team, '(All)' AS Descr
UNION ALL
SELECT 'AAA' , 'AAA'
UNION ALL
SELECT 'BBB' , 'BBB'
Table Mytable
ColumnA Varchar(5)
Values for ColumnA
'AAA'
'AAA 1'
'AAA 2'
'BBB'
'BBB 1'
'BBB 2'
SELECT * FROM Mytable
WHERE ColumnA IN (SELECT * FROM SplitListString(#Team, ',')))
Split function
CREATE FUNCTION [dbo].[SplitListString]
(#InputString NVARCHAR(max), #SplitChar CHAR(1))
RETURNS #ValuesList TABLE
(
param NVARCHAR(MAX)
)
AS
BEGIN
DECLARE #ListValue NVARCHAR(max)
DECLARE #TmpString NVARCHAR(max)
DECLARE #PosSeparator INT
DECLARE #EndValues BIT
SET #TmpString = LTRIM(RTRIM(#InputString));
SET #EndValues = 0
WHILE (#EndValues = 0) BEGIN
SET #PosSeparator = CHARINDEX(#SplitChar, #TmpString)
IF (#PosSeparator) > 1 BEGIN
SELECT #ListValue = LTRIM(RTRIM(SUBSTRING(#TmpString, 1, #PosSeparator -1 )))
END
ELSE BEGIN
SELECT #ListValue = LTRIM(RTRIM(#TmpString))
SET #EndValues = 1
END
IF LEN(#ListValue) > 0 BEGIN
INSERT INTO #ValuesList
SELECT #ListValue
END
SET #TmpString = LTRIM(RTRIM(SUBSTRING(#TmpString, #PosSeparator + 1, LEN(#TmpString) - #PosSeparator)))
END
RETURN
END
You can't. But, you can make the like work like the like:
select *
from mytable t join
SplitListString(#Team, ',') s
on t.ColumnA like '%'+s.param+'%'
That is, move the split list to an explicit join. Replace with the actual column name returned by the function, and use the like function.
Or, if you prefer:
select *
from mytable t cross join
SplitListString(#Team, ',') s
where t.ColumnA like '%'+s.param+'%'
The two versions are equivalent and should produce the same execution plan.
Better approach would be to have a TeamsTable (teamID, teamName, ...) and teamMembersTable (teamMemberID, teamID, teamMemberDetails, ...).
Then you an build your dropdown list as
SELECT ... FROM TeamsTable ...;
and
SELECT ... FROM teamMembersTable WHERE teamID IN (valueFromYourDropDown);
Or you can just store your teamID or teamName (or both) in your (equivalent of) teamMembersTable
You're not going to get IN to work the same as LIKE without a lot of work. You could do something like this though (and it would be nice to see some of your actual data though so we could give better solutions):
SELECT *
FROM table
WHERE LEFT(field,3) IN #Parameter
If you'd like better performance, create a code field on your table and update it like this:
UPDATE table
SET codeField = LEFT(field,3)
Then just add an index on that field and run this query to get your results:
SELECT *
FROM table
WHERE codeField IN #Parameter