代码之家  ›  专栏  ›  技术社区  ›  codingguy3000

SQL Server:如何界定此数据?

  •  0
  • codingguy3000  · 技术社区  · 16 年前
    declare @mydata nvarchar(4000)    
    
    set @mydata =  '36|0, 77|5, 132|61'
    

    我有这些数据,我需要进入一个表格。因此,对于第1行,A列为36,B列为0。对于第2行,A列为77,B列为5等。

    最好的方法是什么?

    谢谢

    2 回复  |  直到 16 年前
        1
  •  1
  •   Daniel Renshaw    16 年前

    您需要一个拆分表值函数。网上有很多例子,例如 http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648

    CREATE FUNCTION dbo.Split
    (
        @RowData nvarchar(2000),
        @SplitOn nvarchar(5)
    )  
    RETURNS @RtnValue table 
    (
        Id int identity(1,1),
        Data nvarchar(100)
    ) 
    AS  
    BEGIN 
        Declare @Cnt int
        Set @Cnt = 1
    
        While (Charindex(@SplitOn,@RowData)>0)
        Begin
            Insert Into @RtnValue (data)
            Select 
                Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
    
            Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
            Set @Cnt = @Cnt + 1
        End
    
        Insert Into @RtnValue (data)
        Select Data = ltrim(rtrim(@RowData))
    
        Return
    END
    go
    
    declare @mydata nvarchar(4000)     
    set @mydata =  '36|0, 77|5, 132|61' 
    
    select
        rowid, [1] as col1, [2] as col2
    from
    (
        select
            Row.Id as rowid, Col.Id as colid, Col.Data
        from dbo.Split(@mydata, ',') as Row
            cross apply dbo.Split(Row.Data, '|') as Col
    ) d
    pivot
    (
        min(d.data)
        for d.colid in ([1], [2])
    ) pd
    

    我刚刚选择了我找到的第一个拆分函数。我不认为这是最好的,但它适用于这个例子。

    输出:

    rowi     col1     col2
    1   36  0
    2   77  5
    3   132 61
    
        2
  •  1
  •   gbn    16 年前

    如果数据在一个文件中,您应该能够tp bcp或大容量插入,指定行和列终止符。

    否则,您需要 nested split function

    当然,您也可以将数据作为XML发送到SQL Server。

    推荐文章