Ecco un metodo abbastanza veloce per dividere le stringhe utilizzando solo T-SQL e parametro di ingresso è solo una stringa. È necessario disporre di una tabella e una funzione (come descritto di seguito) già configurate per utilizzare questo metodo.
creare questa tabella:
CREATE TABLE Numbers (Number int not null primary key identity(1,1))
DECLARE @n int
SET @n=1
SET IDENTITY_INSERT Numbers ON
WHILE @N<=8000
BEGIN
INSERT INTO Numbers (Number) values (@n)
SET @[email protected]+1
END
SET IDENTITY_INSERT Numbers OFF
creare questa funzione per dividere la matrice di stringhe (ho altre versioni, in cui vengono eliminati sezioni vuote e quelli che non restituiscono numeri di riga):
CREATE FUNCTION [dbo].[FN_ListAllToNumberTable]
(
@SplitOn char(1) --REQUIRED, the character to split the @List string on
,@List varchar(8000) --REQUIRED, the list to split apart
)
RETURNS
@ParsedList table
(
RowNumber int --REQUIRED, the list to split apart
,ListValue varchar(500) --OPTIONAL, the character to split the @List string on, defaults to a comma ","
)
AS
BEGIN
--this will return empty rows, and row numbers
INSERT INTO @ParsedList
(RowNumber,ListValue)
SELECT
ROW_NUMBER() OVER(ORDER BY number) AS RowNumber
,LTRIM(RTRIM(SUBSTRING(ListValue, number+1, CHARINDEX(@SplitOn, ListValue, number+1)-number - 1))) AS ListValue
FROM (
SELECT @SplitOn + @List + @SplitOn AS ListValue
) AS InnerQuery
INNER JOIN Numbers n ON n.Number < LEN(InnerQuery.ListValue)
WHERE SUBSTRING(ListValue, number, 1) = @SplitOn
RETURN
END
go
ecco un esempio di come dividere il parametro a parte:
CREATE PROCEDURE TestPass
(
@ArrayOfInts varchar(255) --pipe "|" separated list of IDs
)
AS
SET NOCOUNT ON
DECLARE @TableIDs TABLE (RowNumber int, IDValue int null)
INSERT INTO @TableIDs (RowNumber, IDValue) SELECT RowNumber,CASE WHEN LEN(ListValue)<1 then NULL ELSE ListValue END FROM dbo.FN_ListAllToNumberTable('|',@ArrayOfInts)
SELECT * FROM @TableIDs
go
questo è basso d on: http://www.sommarskog.se/arrays-in-sql.html
La mia reazione iniziale alla tabella "Numeri" era simile alla tua. Si scopre che si tratta di un metodo ampiamente accettato per questo e altri compiti simili. E 'stato reso popolare da Jeff Moden (il più stimato). Vedi questi articoli per discussioni approfondite: ["La tabella" Numeri "o" Tally ": che cos'è e come sostituisce un ciclo."] (Http://www.sqlservercentral.com/articles/TSQL/62867/) e ["Passing Parameters as ... Arrays"] (http://www.sqlservercentral.com/articles/T-SQL/63003/) – kmote