T-SQL动态表创建

时间:2011-05-05 14:31:56

标签: sql sql-server tsql csv

所以这是我上一期的问题

我有一个看起来像这样的字符串:

Acc_id,Field label,Data point

我想使用像

这样的东西从上面的字符串创建一个表
CREATE TABLE #temp
    (Acc_id         NVARCHAR(MAX), 
     Field label    REAL,
     Data point     REAL) 

逗号分隔列 - 它需要是动态的,因此如果出现更多列,则会在表中创建。

更新: 这就是我到目前为止所拥有的网络,但我需要制作第一列NVARCHAR和其余的REAL,而不是相反。

  declare @path NVARCHAR(MAX)
    SET @path = 'c:\temp\Book2.txt'

        declare @execSQL nvarchar(1000)
        declare @tempstr varchar(1000)
        declare @col varchar(1000)
        declare @table nvarchar(1000)

        -- Create a temp table to with one column to hold the first row of the csv file



          CREATE TABLE #tbl (line VARCHAR(1000))
           SET @execSQL = 
                'BULK INSERT #tbl  
                FROM ''' + @path + '''  
                WITH (  
                         FIELDTERMINATOR ='','',
                         FIRSTROW = 1,  
                         ROWTERMINATOR = ''\n'',
                         LASTROW = 1 
                      )         
               ' 

           EXEC sp_executesql @stmt=@execSQL 

        update #tbl set line = REPLACE(line,' ','_') where line like '% %'


           SET @col = ''
           SET @tempstr = (SELECT TOP 1 RTRIM(REPLACE(Line, CHAR(9), ',')) FROM #tbl)
           DROP TABLE #tbl
           WHILE CHARINDEX(',',@tempstr) > 0
            BEGIN           

               SET @col=@col + LTRIM(RTRIM(SUBSTRING(@tempstr, 1, CHARINDEX(',',@tempstr)-1))) + ' varchar(100),'     

               SET @tempstr = SUBSTRING(@tempstr, CHARINDEX(',',@tempstr)+1, len(@tempstr)) 
            END
            SET @col = @col + @tempstr + ' real'

           IF Object_id('tempdb..##temptable') IS NOT NULL 
           DROP TABLE #temptable 

           SET @table = 'create table ##temptable (' + @col + ')'

           EXEC sp_executesql @stmt=@table


        -- Load data from csv
           SET @execSQL = 
                'BULK INSERT ##temptable
                FROM ''' + @path + '''  
                WITH (  
                         FIELDTERMINATOR ='','',
                         FIRSTROW = 2,  
                         ROWTERMINATOR = ''\n''              
                      )         
               '  

           EXEC sp_executesql @stmt=@execSQL 

谢谢 罗布

2 个答案:

答案 0 :(得分:2)

以下适合我想做的事情

declare @path NVARCHAR(MAX)

SET @path = 'c:\temp\Book2.txt'

    declare @execSQL nvarchar(1000)
    declare @tempstr varchar(1000)
    declare @col varchar(1000)
    declare @table nvarchar(1000)

    -- Create a temp table to with one column to hold the first row of the csv file

  IF Object_id('tempdb..#tbl') IS NOT NULL 
       DROP TABLE #tbl 

      CREATE TABLE #tbl (line VARCHAR(1000))
       SET @execSQL = 
            'BULK INSERT #tbl  
            FROM ''' + @path + '''  
            WITH (  
                     FIELDTERMINATOR ='','',
                     FIRSTROW = 1,  
                     ROWTERMINATOR = ''\n'',
                     LASTROW = 1 
                  )         
           ' 

       EXEC sp_executesql @stmt=@execSQL 

    update #tbl set line = REPLACE(line,' ','_') where line like '% %'


       SET @col = ''
       SET @tempstr = (SELECT TOP 1 RTRIM(REPLACE(Line, CHAR(9), ',')) FROM #tbl)

       DROP TABLE #tbl

    SET @col=@col + LTRIM(RTRIM(SUBSTRING(@tempstr, 1, CHARINDEX(',',@tempstr)-1))) + ' nvarchar(max),'     
    SET @tempstr = SUBSTRING(@tempstr, CHARINDEX(',',@tempstr)+1, len(@tempstr))

       WHILE CHARINDEX(',',@tempstr) > 0
        BEGIN           

           SET @col=@col + LTRIM(RTRIM(SUBSTRING(@tempstr, 1, CHARINDEX(',',@tempstr)-1))) + ' nvarchar(max),'     

           SET @tempstr = SUBSTRING(@tempstr, CHARINDEX(',',@tempstr)+1, len(@tempstr)) 
        END
        SET @col = @col + @tempstr + ' real'


       IF Object_id('tempdb..##temptable') IS NOT NULL 
       DROP TABLE ##temptable 

       SET @table = 'create table ##temptable (' + @col + ')'

       EXEC sp_executesql @stmt=@table


    -- Load data from csv
       SET @execSQL = 
            'BULK INSERT ##temptable
            FROM ''' + @path + '''  
            WITH (  
                     FIELDTERMINATOR ='','',
                     FIRSTROW = 2,  
                     ROWTERMINATOR = ''\n''              
                  )         
           '  

       EXEC sp_executesql @stmt=@execSQL 

select * from ##temptable

答案 1 :(得分:0)

我建议做一个while循环并将一个字符串连接起来为你的表创建。这可以用于通过分隔符分隔的列表进行解析。类似于下面的内容应该让你开始。

set @IDList='Field1,Field2,Field3,'
set @i=1
set @pos =  patindex('%,%' , @IDList)
while @pos <> 0 begin
    -- Loop through Elements
    set @CurrentID= isnull(left(@IDList, @pos-1),null)

    set @SQLConstructor=@SQLConstructor+',sum('+@CurrentID+') as Column'+@si

    --- Reset loop
    set @IDList = stuff(@IDList, 1, @pos, '')
    set @pos =  patindex('%,%' , @IDList)
    set @i=@i+1
end