我有这个存储过程,我将@CourseID
作为
|CRS0001095|CRS0001223|CRS0001224|CRS0001225|CRS0001229|CRS0001238|CRS000124
来自Web应用程序。但我想将此字符串替换为
'CRS0001095', 'CRS0001223', 'CRS0001224', 'CRS0001225', 'CRS0001229', 'CRS0001238', 'CRS000124'
这样我就可以将此字符串传递给我的查询。
我尝试了Replace
,但这会导致错误。我该如何更改该字符串?
ALTER PROCEDURE [dbo].[LSS_e_test_sp]
@TRANTYPE VARCHAR(30)='',
@PARAM1 VARCHAR(30)='',
@PARAM2 VARCHAR(30)='',
@PARAM3 VARCHAR(30)='',
@PARAM4 VARCHAR(30)='',
@PARAM5 VARCHAR(3000)=''
AS
DECLARE
@WORKORDERNO VARCHAR(20),
@EVENTPOINT VARCHAR(30),
@LASTEDITBY VARCHAR(30),
@ERRMSG VARCHAR(500),
@ProductionLine VARCHAR(100),
@CourseID VARCHAR(3000),
@OperatorsTraLevel VARCHAR(30),
@reqOperatorLevel VARCHAR(30)
IF @TRANTYPE = 'getOperatorLavel'
BEGIN
SET @WORKORDERNO = @PARAM1
SET @EVENTPOINT = @PARAM2
SET @LASTEDITBY = @PARAM3
SET @CourseID = @PARAM5
Print @WORKORDERNO
Print @EVENTPOINT
Print @LASTEDITBY
Print @CourseID
select @OperatorsTraLevel = MAX(convert(real, TraingLavel))
from ftx_tm_courselevelMapping
where coursenumber in (@CourseID)
print @OperatorsTraLevel
RETURN 0
END
答案 0 :(得分:1)
尝试另一条路线:
imports
甚至不要拆分WHERE CHARINDEX(coursenumber,@CourseID)>0
并选择@CourseID
字符串中coursenumber
所在的数据。
答案 1 :(得分:1)
我假设你在IN Clause中使用@CourseID,所以你可以做类似的事情
declare @str nvarchar(max) = '|CRS0001095|CRS0001223|CRS0001224|CRS0001225|CRS0001229|CRS0001238|CRS000124';
declare @ret_list as table ( cr_id nvarchar(max) );
declare @pos int;
declare @cr_id nvarchar(max)
while CHARINDEX('|', @str) > 0
begin
select @pos = CHARINDEX('|', @str);
select @cr_id = substring(@str, 1, @pos-1);
insert into @ret_list (cr_id) values (@cr_id);
select @str = SUBSTRING(@str, @pos+1, LEN(@str) - @pos)
end
select * from @ret_list where cr_id not like ''
之后,请替换以下内容:
select @OperatorsTraLevel = MAX(convert (real, TraingLavel)) from ftx_tm_courselevelMapping where coursenumber in (@CourseID)
带
select @OperatorsTraLevel = MAX(convert (real, TraingLavel)) from ftx_tm_courselevelMapping where coursenumber in (select cr_id from @ret_list where cr_id not like '')
你应该是金色的!
答案 2 :(得分:0)
如果您的MS SQL Server是2016,那么您可以享受string_split
功能。
...where si in (select value from string_split(@CourseID,'|'))
否则,如果MS SQL Server是2008或更新版本,则可以在查询中拆分字符串。
;with dat(x) as (
select cast( '<s>'+replace(@CourseID,'|','</s><s>')+'</s>' as xml)
)
select @OperatorsTraLevel = MAX(convert (real, TraingLavel))
from ftx_tm_courselevelMapping cross join dat
where coursenumber in (select t.v.value('.[1]','varchar(20)') from x.nodes('s') t(v))