2010-09-17 15 views
6
-- Given a CSV string like this: 

declare @roles varchar(800) 
select @roles = 'Pub,RegUser,ServiceAdmin' 

-- Question: How to get roles into a table view like this: 

select 'Pub' 
union 
select 'RegUser' 
union 
select 'ServiceAdmin' 

Po wysłaniu tego, zacząłem grać z jakiegoś dynamicznego SQL. To wydaje się działać, ale wydaje się, że może być pewne zagrożenie bezpieczeństwa przy użyciu dynamicznego SQL - myśli na ten temat?Najbardziej zwięzły sposób przekształcenia łańcucha CSV w tabelę w TSQL?

declare @rolesSql varchar(800) 
select @rolesSql = 'select ''' + replace(@roles, ',', ''' union select ''') + '''' 
exec(@rolesSql) 

Odpowiedz

10

Zobacz moje odebrać od here

Ale w zasadzie to:

utworzyć tę funkcję w swojej DB:

CREATE FUNCTION dbo.Split(@origString varchar(max), @Delimiter char(1))  
returns @temptable TABLE (items varchar(max))  
as  
begin  
    declare @idx int  
    declare @split varchar(max)  

    select @idx = 1  
     if len(@origString)<1 or @origString is null return  

    while @idx!= 0  
    begin  
     set @idx = charindex(@Delimiter,@origString)  
     if @idx!=0  
      set @split= left(@origString,@idx - 1)  
     else  
      set @split= @origString 

     if(len(@split)>0) 
      insert into @temptable(Items) values(@split)  

     set @origString= right(@origString,len(@origString) - @idx)  
     if len(@origString) = 0 break  
    end 
return  
end 

a następnie wywołać funkcję i przechodzą w ciągu chcesz podzielić.

Select * From dbo.Split(@roles, ',') 
+0

Dzięki, to jest świetna funkcja. –

+2

TVF tak? Czy nie byłoby SELECT * FROM dbo.Split (@roles, ',')? – Sinaesthetic

6

Jeśli pracujesz z poziomem zgodności programu SQL Server 130, funkcja STRING_SPLIT jest obecnie najbardziej zwięzłą dostępną metodą.

LINK: https://msdn.microsoft.com/en-gb/library/mt684588.aspx

Zastosowanie:

SELECT * FROM string_split('Pub,RegUser,ServiceAdmin',',') 

RESULT: 

value 
----------- 
Pub 
RegUser 
ServiceAdmin 
0

za pomocą wbudowanego w parsowania XML jest również opcję SQL Server. Oczywiście, to glosuje nad wszystkimi niuansami zgodnego z RFC-4180 pliku CSV.

-- Given a CSV string like this: 
declare @roles varchar(800) 
select @roles = 'Pub,RegUser,ServiceAdmin' 

-- Here's the XML way 
select split.csv.value('.', 'varchar(100)') as value 
from (
    select cast('<x>' + replace(@roles, ',', '</x><x>') + '</x>' as xml) as data 
) as csv 
cross apply data.nodes('/x') as split(csv) 

Jeśli używasz SQL 2016+, używając string_split jest lepsza, ale jest to wspólny sposób to zrobić przed SQL 2016

Powiązane problemy