2017-06-26 68 views
0

我有以下是與下面的值返回一個變量@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 
    [email protected] 
AND 
    DimdateId= @DimdateId 

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

添加預期輸出 –

+0

預期輸出:選擇 '[5.00]', '[5.00]',「[ 1.00]','[35.00]','[1.00]','[1.00]','[1.00]','[1.00]','[1.00]','[1.00]' –

回答

1

試試這個下面

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 '[email protected] 
    EXECUTE @Sql 
    PRINT @Sql 

它打印像下面

SELECT '[5.00]', '[5.00]', '[1.00]', '[35.00]', '[1.00]', '[1.00]', '[1.00]', '[1.00]', '[1.00]', '[1.00]' 
0

此代碼是不是我的。這是由約翰·卡佩萊蒂(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 
+0

請停止發佈我的代碼沒有適當的歸屬。 https://meta.stackexchange.com/questions/160071/what-to-do-when-plagiarism-is-discovered –