假设我有一个包含3行的表 - 每行包含一个CSV,我可以保证只有1个逗号
xxx,111
yyy,222
zzz,333
如何选择表格,以便生成的表格包含2列:
xxx 111
yyy 222
zzz 333
我试过了SELECT split(item,',') FROM A
但很明显,这不会奏效。 有没有使用游标的功能方法?
我正在使用SQL Server 2008
答案 0 :(得分:3)
虽然没有像split()这样简单的功能方式。有一种不使用游标的方法:
SELECT
SUBSTRING(item, 1,
CHARINDEX(',', item) - 1
) AS Field1,
SUBSTRING(item, CHARINDEX(',', item) + 1,
LEN(item) - CHARINDEX(',', item)
) AS Field2
FROM A
答案 1 :(得分:1)
看看这篇文章Split Function in Sql Server to break Comma-Separated Strings into Table。我认为这将解决您的问题。
答案 2 :(得分:1)
我正在使用此存储过程将.csv文件加载到现有表中,它可能会对您有所帮助。它会将匹配模式的文件夹中的所有csv文件加载到表中。你必须通过它
这不是百分百百分之百的万无一失(例如避免文件名或空格过于宽松),但您可以根据需要进行更改。
-- ============================================================
-- Author: László Tenki
-- Create date: 2011-06-20
-- Description: Data integration script for loading Excel files
-- using the standard MS data connectivity pack
-- Microsoft.ACE.OLEDB.12.0
-- ============================================================
ALTER procedure [di].[genericCSVImporter]
-- parameters for the stored procedure
@folder varchar(500), @fileNamePattern varchar(100),
@table varchar(128), @moveProcessed bit,
@fieldDelimiter varchar(1), @firstRow int, @formatFile nvarchar(25)
as
begin
declare @query varchar(1000)
declare @filename varchar(200)
declare @formatFilePath varchar(200)
declare @dir table ([name] varchar(200))
set @query ='master.dbo.xp_cmdshell "dir ' + @folder + '\' + @fileNamePattern + ' /b"'
set @query = replace(@query, '\\', '\')
insert into @dir exec (@query)
delete from @dir where name is NULL
declare myc cursor for select [name] from @dir where [name]<> 'File Not Found' order by [name]
open myc
fetch next from myc into @filename
while @@fetch_status = 0
begin
set @filename = @folder + '\' + @filename
set @filename = replace(@filename, '\\', '\')
set @formatFilePath = replace(@folder + '\' + @formatFile, '\\', '\')
set @query ='BULK INSERT ' + @table + ' FROM ''' + @filename +
''' WITH (FIELDTERMINATOR = ''' + @fieldDelimiter + ''', ROWTERMINATOR = ''\n'', ' +
'FIRSTROW = ' + cast(@firstRow as nvarchar(10)) + ', CODEPAGE = ''ACP'', ' +
'FORMATFILE=''' + @formatFilePath + ''')'
print @query
exec (@query)
if @moveProcessed=1
begin
set @query = 'master.dbo.xp_cmdshell "copy /Y ' + @filename + ' ' + @folder +'\done"'
exec (@query)
set @query = 'master.dbo.xp_cmdshell "del /Q ' + @filename + '"'
exec (@query)
end
fetch next from myc into @filename
end
close myc
deallocate myc
end