問題:
您有一個包含兩列的表,Code和宣言。聲明列包含以逗號分隔的值清單。您需要將此資料轉換為行,每行代表對應程式碼的單獨聲明。
解決方案:
解決此問題的一種方法是建立一個自訂 SQL函數:
create FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1)) returns @temptable TABLE (items varchar(MAX)) as begin declare @idx int declare @slice varchar(8000) select @idx = 1 if len(@String)<1 or @String is null return while @idx!= 0 begin set @idx = charindex(@Delimiter,@String) if @idx!=0 set @slice = left(@String,@idx - 1) else set @slice = @String if(len(@slice)>0) insert into @temptable(Items) values(@slice) set @String = right(@String,len(@String) - @idx) if len(@String) = 0 break end return end;
然後,您可以使用外部應用程式在查詢中利用此函數來連接到現有的表:
select t1.code, s.items declaration from yourtable t1 outer apply dbo.split(t1.declaration, ',') s
此查詢將產生所需的結果:
| CODE | DECLARATION | ----------------------- | 123 | a1-2 nos | | 123 | a2- 230 nos | | 123 | a3 - 5nos |
或者,您可以使用CTE(通用表表達式)版本,其操作類似:
;with cte (code, DeclarationItem, Declaration) as ( select Code, cast(left(Declaration, charindex(',',Declaration+',')-1) as varchar(50)) DeclarationItem, stuff(Declaration, 1, charindex(',',Declaration+','), '') Declaration from yourtable union all select code, cast(left(Declaration, charindex(',',Declaration+',')-1) as varchar(50)) DeclarationItem, stuff(Declaration, 1, charindex(',',Declaration+','), '') Declaration from cte where Declaration > '' ) select code, DeclarationItem from cte
以上是如何將 SQL 列中的逗號分隔值轉換為單獨的行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!