如何将动态变量值拆分为单个列?

时间:2017-06-26 10:58:36

标签: sql sql-server sql-server-2008

我有以下代码返回变量@colsrate,其中包含以下值:

'[5.00],[5.00],[1.00],[35.00],[1.00],[1.00],[1.00],[1.00],[1.00],[1.00]' 

我需要将这些单独的值转换为单个列。我怎样才能做到这一点?谢谢。

SELECT 
    CAST((CAST(Rate AS DECIMAL(18,2))) AS NVARCHAR(255))AS Rate 
    ,LEFT((CAST(StartDate AS NVARCHAR(255))), 11) AS StartDate
    INTO #TempTab
    FROM RepoCost.vwCurrencyRate
WHERE 
    CurrencyNameFrom = @CurrencyNameFrom
AND 
    CurrencyNameTo=@CurrencyNameTo
AND 
    DimdateId= @DimdateId

SET @colsrate =  STUFF((SELECT ','+QUOTENAME(Rate)
                    FROM #TempTab
      FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)') 
,1,1,'')

2 个答案:

答案 0 :(得分:1)

请尝试以下

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name thewhozoo.com www.thewhozoo.com;
    return 301 https://$host$request_uri;
}

打印如下

IF OBJECT_ID('Tempdb..#Temp') IS NOT NULL
Drop table #Temp
Declare @DyValue TABLE (Value nvarchar(max))
INSERT INTO @DyValue(Value)
SELECT '[5.00],[5.00],[1.00],[35.00],[1.00],[1.00],[1.00],[1.00],[1.00],[1.00]' 

Declare @DynamicCol nvarchar(max),@Sql nvarchar(max)

SELECT * INTO #Temp FROM
(
SELECT Row_number()Over(Order by (SELECT NULL)) AS ID,Split.a.value('.', 'VARCHAR(1000)') AS Value
            FROM  (
                SELECT  CAST('<S>' + REPLACE(Value, ',', '</S><S>') + '</S>' AS XML) AS Value
                FROM @DyValue
                ) AS A
            CROSS APPLY Value.nodes('/S') AS Split(a)
            )Dt


    SELECT @DynamicCol=STUFF((SELECT ', ' + ''''+CAST( Value AS Varchar(10))+'''' From #Temp
            FOR XML PATH ('')),1,1,'')  
            SELECT @DynamicCol AS ExpectedValue

    SET @Sql ='SELECT '+@DynamicCol 
    EXECUTE @Sql
    PRINT @Sql

答案 1 :(得分:0)

这段代码不是我的。这是John Cappelletti的解决方案( here's the original link

但完全符合您的需要

Declare @YourTable table (SomeCol varchar(max))
Insert Into @YourTable values
('[5.00],[5.00],[1.00],[35.00],[1.00],[1.00],[1.00],[1.00],[1.00],[1.00]')


Select B.*
 From  @YourTable A
 Cross Apply (
                Select Pos1 = ltrim(rtrim(xDim.value('/x[1]','varchar(max)')))
                      ,Pos2 = ltrim(rtrim(xDim.value('/x[2]','varchar(max)')))
                      ,Pos3 = ltrim(rtrim(xDim.value('/x[3]','varchar(max)')))
                      ,Pos4 = ltrim(rtrim(xDim.value('/x[4]','varchar(max)')))
                      ,Pos5 = ltrim(rtrim(xDim.value('/x[5]','varchar(max)')))
                      ,Pos6 = ltrim(rtrim(xDim.value('/x[6]','varchar(max)')))
                      ,Pos7 = ltrim(rtrim(xDim.value('/x[7]','varchar(max)')))
                From  (Select Cast('<x>' + replace((Select replace(A.SomeCol,',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml) as xDim) as A 
             ) B