动æ€åœ°æ ¹æ®è¾“å…¥å‚æ•°å°†ä¸åŒæ•°é‡çš„值æ’入过程

时间:2016-12-30 12:14:38

标签: sql sql-server-2008 stored-procedures

parseMessage ('I':_) = Info
parseMessage ('W':_) = Warning
parseMessage _       = Error 1

有什么办法å¯ä»¥åŠ¨æ€åœ°åœ¨æˆ‘的临时表中æ’å…¥ä¸åŒæ•°é‡çš„åå­—å—?

2 个答案:

答案 0 :(得分:2)

没有拆分/解æžåŠŸèƒ½

这里我们将分隔符作为|传递这å¯ä»¥æ˜¯ä½ å–œæ¬¢çš„任何东西

Declare @Names varchar(max) = 'Smith, John|Williams, Bill'

Insert Into #MyTempTable(Name)
Select RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From  (Select x = Cast('<x>'+ replace((Select @Names as [*] For XML Path('')),'|','</x><x>')+'</x>' as xml).query('.')) as A 
Cross Apply x.nodes('x') AS B(i)

使用拆分/解æžåŠŸèƒ½

Declare @Names varchar(max) = 'Smith, John|Williams, Bill'

Insert Into #MyTempTable(Name)
Select RetVal from [dbo].[udf-Str-Parse] (@Names,'|')

UDF如果需è¦

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (  
    Select RetSeq = Row_Number() over (Order By (Select null))
          ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
    From  (Select x = Cast('<x>'+ replace((Select @String as [*] For XML Path('')),@Delimiter,'</x><x>')+'</x>' as xml).query('.')) as A 
    Cross Apply x.nodes('x') AS B(i)
);
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')

答案 1 :(得分:1)

ä¸æ˜¯ä¼ é€’å¯å˜æ•°é‡çš„å‚数,而是å‘é€ä¸€ä¸ªé€—å·åˆ†éš”çš„å称列表并在存储过程中,使用split函数æ¥æ£€ç´¢å称值并æ’入。

CREATE PROC InsertData_To_TempTable
@NameList VARCHAR(MAX)
AS
BEGIN

    INSERT INTO #MyTempTable(Name)
    SELECT Item
    FROM dbo.SplitString(@NameList)
END

然åŽè‡´ç”µ

EXEC InsertData_To_TempTable 'A,B,C'

EXEC InsertData_To_TempTable 'A,B,C,D,E'

没有内置的分割功能,所以这里åªæœ‰ä¸€ä¸ªuser defined function.

CREATE FUNCTION SplitString
(    
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
)
RETURNS @Output TABLE (
      Item NVARCHAR(1000)
)
AS
BEGIN
      DECLARE @StartIndex INT, @EndIndex INT

      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
      BEGIN
            SET @Input = @Input + @Character
      END

      WHILE CHARINDEX(@Character, @Input) > 0
      BEGIN
            SET @EndIndex = CHARINDEX(@Character, @Input)

            INSERT INTO @Output(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)

            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
      END

      RETURN
END
GO

您å¯ä»¥æœç´¢å…¶ä»–具有更好性能(ä¸ä½¿ç”¨while循环)的拆分功能。 SQL Server 2016引入了split功能。 这是various split functions的性能分æžçš„ç»ä½³æ¥æºã€‚