Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

SQL Server 2008 Dividi stringa dal campo nel record

Usa CROSS APPLY insieme alla tua divisione UDF. Il divisore di stringhe che sto usando per il mio esempio proviene da qui .

/* Create function for purposes of demo */
CREATE FUNCTION [dbo].[fnParseStringTSQL] (@string NVARCHAR(MAX),@separator NCHAR(1))
RETURNS @parsedString TABLE (string NVARCHAR(MAX))
AS 
BEGIN
   DECLARE @position int
   SET @position = 1
   SET @string = @string + @separator
   WHILE charindex(@separator,@string,@position) <> 0
      BEGIN
         INSERT into @parsedString
         SELECT substring(@string, @position, charindex(@separator,@string,@position) - @position)
         SET @position = charindex(@separator,@string,@position) + 1
      END
     RETURN
END
go

/* Set up sample data */
declare @t table (
    IR int,
    CR varchar(100)
)

insert into @t
    (IR, CR)
    select 1, '1,2' union all
    select 2, '3' union all
    select 3, '4,5,6'

/* Here's the query that solves the problem */
select t.IR, p.string
    from @t t
        cross apply [dbo].[fnParseStringTSQL](t.CR,',') p


/* clean up after demo */
drop function [dbo].[fnParseStringTSQL]