我有一个 sql 查询,它从 csv 文件中导入数据,然后将该数据与我的数据库中的记录进行匹配,以确保记录确实存在,完成后它会将文件导出到 xls 文件,当它导出到文件时结果将所有输出设置在一行中,其中包含像它导入的行。例如。导入第 10 行,匹配第 7 行。导出第 1 行而不是 7 行:
DROP TABLE CSVdataRaw,#FileList,#TmpID/ #Failures,#Success, / --,#ReverseFile
IF NOT EXISTS (SELECT * FROM SYS.tables WHERE name = 'CSVdataRaw')
BEGIN
CREATE TABLE CSVdataRaw
(
CellNumber varchar(12),
SMS_MSG varchar(250)
)
END
Create Table #FileList (
SMSFilename Varchar(512))
Declare @Path varchar(256) = 'dir C:\FileImport\Inbox\'
Declare @Command varchar(1024) = @Path+' /A-D /B'
--PRINT @Command
Insert #FileList
Exec Master.dbo.xp_cmdshell @Command
delete #FileList where SMSFilename is Null
Declare @File varchar (255) =
( SELECT top 1 * FROM #FileList
where SMSFilename like 'SMS%')
print @File
Declare @SMSFilename Varchar (255)
Set @SMSFilename = 'C:\FileImport\Inbox\'
Set @SMSFilename = @SMSFilename + @File -- + ''''
declare @BulkInsert varchar(MAX);
set @BulkInsert = 'BULK INSERT [CSVdataRaw]
From ' + char(39) + @SMSFilename +char(39)+
' With (ROWTERMINATOR = ''\n'', FIELDTERMINATOR = '','', Firstrow = 1)'
--print @BulkInsert
exec(@BulkInsert)
ALTER TABLE CSVdataRaw ADD ID INT IDENTITY
GO
alter table CSVDataRaw add Matterno Varchar (50)
GO
update CSVDataRaw set Matterno = (SELECT TOP 1 H_MID FROM History WHERE H_PhoneNumber = CSVDataRaw.CellNumber)
GO
alter table CSVDataRaw add H_Description varchar(50)
GO
update CSVdataRaw set H_Description = (select top 1 H_IDX from History with (nolock) where H_Description = CSVdataRaw.SMS_MSG)
GO
delete from CSVDataRaw where Matterno is null
CREATE TABLE #TmpID
(
ID INT,
Note VARCHAR(255)
)
DECLARE @Line varchar(MAX)
DECLARE @FileName varchar(255)
DECLARE @Row int
--INSERT HEADER
SET @FileName = 'C:\FileImport\SMS_History_' + replace(replace(replace(CONVERT(varchar,getdate(),120),' ',''),'-',''),':','') + '.xls'
SET @Line = 'Profile=0,Product=0,Client=0,ImportType=20,Delimiter= ,' + CHAR(13) + CHAR(10)
DELETE #TmpID
Insert into #TmpID (ID, Note)
select CellNumber, SMS_MSG
from CSVDataRaw
SELECT @Line = @Line + Note FROM #TmpID
--print @Line
EXEC dbo.uspWriteToFile @FileName, @Line
--print @Line
DROP TABLE CSVdataRaw,#TmpID,#FileList
Create Table #FileList (
SMSFilename Varchar(512))
Declare @Path varchar(256) = 'dir C:\FileImport\Inbox\'
Declare @Command varchar(1024) = @Path+' /A-D /B'
Insert #FileList
Exec Master.dbo.xp_cmdshell @Command
delete #FileList where SMSFilename is Null
Declare @File varchar (255) =
(SELECT top 1 * FROM #FileList
where SMSFilename like 'SMS%')
print @File
Declare @SMSFilename Varchar (255)
Set @SMSFilename = 'move /y C:\FileImport\Inbox\ C:\FileImport\Archive\' --Here you are setting a variable
Set @SMSFilename = @SMSFilename + @File + ''''
exec xp_cmdshell 'move /y C:\FileImport\Inbox\ C:\FileImport\Archive' --This part you are actually MOVING the file
DROP TABLE #FileList