如何通过执行以下功能获得所需的输出

时间:2012-01-25 14:44:06

标签: sql-server

我的问题是我写了一个函数

ALTER FUNCTION [dbo].StringSplitting_23012012 (@string NVARCHAR(MAX),
@Delimiter NVARCHAR(1))
RETURNS
 @Temp TABLE (string NVARCHAR(MAX))
AS 
BEGIN
   DECLARE @p int
   SET @p = 0
   --SET @string = (@string + @Delimiter)
   WHILE charindex(@Delimiter,@string) < 0 --,@p) <> 0 
     BEGIN
       INSERT into @Temp
       SELECT substring(@string,@p,charindex(@Delimiter,@string)) --+ @p)
       --select   substring(@string,5,15) SET @p = charindex(@Delimiter,@string) --1
     END
   RETURN
END 

并将字符串传递给该函数

SELECT * FROM [dbo].StringSplitting('SPLA-WINSVRSTD #P19-1999 QTY1:
SPLA-WINSVRSTD #P12-2999 QTY2 : SPLA-WINSVRSTD #P19-1399 QTY3 : 
SPLA-WINSVRSTD #P19-1399 QTY4 : SPLA-WINSVRSTD #P59-5999 QTY5 : 
SPLA-WINSVRSTD #P69-6999 QTY6 : SPLA-WINSVRSTD #P79-7999 QTY7 : 
SPLA-WINSVRSTD #P69-6999 QTY8',':')

我将输出作为

SPLA-WINSVRSTD #P19-1999 QTY1
SPLA-WINSVRSTD #P12-2999 QTY2 
SPLA-WINSVRSTD #P19-1399 QTY3   
SPLA-WINSVRSTD #P19-1399 QTY4 
SPLA-WINSVRSTD #P59-5999 QTY5 
SPLA-WINSVRSTD #P69-6999 QTY6 
SPLA-WINSVRSTD #P79-7999 QTY7 
SPLA-WINSVRSTD #P69-6999 QTY8

到目前为止它还可以,但我需要像

这样的输出
SPLA P12-2999 QTY2 
SPLA P19-1399 QTY3   
SPLA P19-1399 QTY4 
SPLA P59-5999 QTY5 
SPLA P69-6999 QTY6 
SPLA P79-7999 QTY7 
SPLA P69-6999 QTY8

请你帮我解决如何编写功能或程序以获得所需的输出

1 个答案:

答案 0 :(得分:0)

我建议使用REPLACE函数 - 就像这样:

[为清晰起见而格式化]

SELECT * FROM [dbo].StringSplitting(
REPLACE('SPLA-WINSVRSTD #P19-1999 QTY1:
         SPLA-WINSVRSTD #P12-2999 QTY2 : SPLA-WINSVRSTD #P19-1399 QTY3 : 
         SPLA-WINSVRSTD #P19-1399 QTY4 : SPLA-WINSVRSTD #P59-5999 QTY5 : 
         SPLA-WINSVRSTD #P69-6999 QTY6 : SPLA-WINSVRSTD #P79-7999 QTY7 : 
         SPLA-WINSVRSTD #P69-6999 QTY8', '-WINSVRSTD #','')
,':')

[用于复制和粘贴]

SELECT * FROM [dbo].StringSplitting(REPLACE(
'SPLA-WINSVRSTD #P19-1999 QTY1 : SPLA-WINSVRSTD #P12-2999 QTY2 : SPLA-WINSVRSTD #P19-1399 QTY3 : SPLA-WINSVRSTD #P19-1399 QTY4 : SPLA-WINSVRSTD #P59-5999 QTY5 : SPLA-WINSVRSTD #P69-6999 QTY6 : SPLA-WINSVRSTD #P79-7999 QTY7 : SPLA-WINSVRSTD #P69-6999 QTY8'
, '-WINSVRSTD #','') ,':')