如何在sql中拆分给定的字符串

时间:2015-12-11 09:10:29

标签: sql-server split

Declare @string VARCHAR(8000)
SELECT @string ='--testname="%SP_FVT_HOME%\Runner.py" --testCommandline="-slot %DPorting% -fvt \"--playlist=AP114 %PVR% --randomseed=%RANDOM_SP% --testdur=%TESTDURATION%\" -Production %PRODUCTION% 

我上面的字符串我想要输出类似下面的

%SP_FVT_HOME%,
%DPorting%,
%PVR%,
%RANDOM_SP%,
%TESTDURATION%,
%PRODUCTION% 

请帮帮我

2 个答案:

答案 0 :(得分:0)

您可以编写函数或存储过程或编写普通代码。像这样:

DECLARE @string VARCHAR(8000)
DECLARE @temp TABLE(string VARCHAR(100))
SELECT @string ='--testname="%SP_FVT_HOME%\Runner.py" --testCommandline="-slot %DPorting% -fvt \"--playlist=AP114 %PVR% --randomseed=%RANDOM_SP% --testdur=%TESTDURATION%\" -Production %PRODUCTION%'
DECLARE @string_result VARCHAR(8000) = ''

WHILE CHARINDEX('%', @string) <> 0
BEGIN
    SELECT @string = REPLACE(@string, LEFT(@string, CHARINDEX('%', @string)), '')
    SELECT @string_result = '%' + LEFT(@string, CHARINDEX('%', @string))
    SELECT @string = REPLACE(@string, LEFT(@string, LEN(@string_result)-1), '')
    INSERT INTO @temp SELECT @string_result
END

SELECT * FROM @temp

答案 1 :(得分:0)

试试这个,虽然可能不是100%可靠:

DECLARE @string VARCHAR(8000)
SELECT @string ='--testname="%SP_FVT_HOME%\Runner.py" --testCommandline="
  -slot %DPorting% -fvt \"--playlist=AP114 %PVR% 
  --randomseed=%RANDOM_SP% --testdur=%TESTDURATION%\" -Production %PRODUCTION%'

;WITH CTE as
(
  SELECT t.c.value('.', 'VARCHAR(2000)') val, row_number() over(ORDER BY (SELECT 1)) rn
  FROM (
    SELECT x = CAST('<t>' + 
      REPLACE(@string, '%', '</t><t>') + '</t>' AS XML)
) a
CROSS APPLY x.nodes('/t') t(c)
)
SELECT '%' + val + '%' FROM CTE 
WHERE rn % 2 = 0

结果:

%SP_FVT_HOME%
%DPorting%
%PVR%
%RANDOM_SP%
%TESTDURATION%
%PRODUCTION%