【发布时间】:2016-03-30 11:34:16
【问题描述】:
能否请您帮我重写以下 CP,以便当它从文件中读取以删除除数字以外的任何其他字符时: 它所做的是读取一个文件,例如 block.txt 并将每一行添加到表中。
USE [db_Test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Cp_ImportBlackList]
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION Acbc
DECLARE @command nvarchar(max)
DECLARE @delcommand varchar(200)
DECLARE @txtfile nvarchar(200)
DECLARE @line nvarchar(2)
DECLARE @andreas nvarchar(200)
set @line='\n'
DECLARE @isExists INT
DECLARE @tempcol int
DECLARE MyCursor cursor fast_forward for
Select Users_ID from Prj_Users
open MyCursor
fetch next from MyCursor
into @tempcol
while @@fetch_status = 0
begin
set @txtfile = 'c:\BlackList\ ' + LTRIM(RTRIM(str(@tempcol))) + '.txt'
exec master.dbo.xp_fileexist @txtfile,
@isExists OUTPUT
if (@isExists =1)
begin
BEGIN TRY
BEGIN TRANSACTION ad
set @command=' BULK INSERT Prj_TempBlackList FROM ''' + @txtfile + ''''
set @command += ' WITH( ROWTERMINATOR = '''+ @line +''' )'
print @command
EXECUTE(@command)
delete Prj_TempBlackList where Tell in(select [BLList_TEll] from prj_BlackList where [BLList_UserID] = @tempcol)
insert into prj_BlackList select DISTINCT Tell,@tempcol from Prj_TempBlackList where Tell not in(select [BLList_TEll] from prj_BlackList where [BLList_UserID] = @tempcol)
delete from Prj_TempBlackList
set @delcommand ='del ' + @txtfile
exec xp_cmdshell @delcommand
print 'end'
COMMIT TRANSACTION ad
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION ad
SELECT ERROR_Message() AS ErrorNumber;
END CATCH
end
else
print 'no'
fetch next from MyCursor
into @tempcol
end
close MyCursor
deallocate MyCursor
set @txtfile = 'c:\BlackList\block.txt'
exec master.dbo.xp_fileexist @txtfile,
@isExists OUTPUT
if (@isExists =1)
begin
BEGIN TRY
BEGIN TRANSACTION ada
set @command=' BULK INSERT Prj_TempBlackList FROM ''' + @txtfile + ''''
set @command += ' WITH( ROWTERMINATOR = '''+@line+''' )'
EXECUTE(@command)
delete Prj_TempBlackList where Tell in(
select [BLList_TEll] from prj_BlackList where [BLList_UserID] is null)
insert into prj_BlackList SELECT DISTINCT Tell,null from
Prj_TempBlackList where Tell not in(
select [BLList_TEll] from prj_BlackList where [BLList_UserID] is null)
delete from Prj_TempBlackList
set @delcommand ='del ' + @txtfile
exec xp_cmdshell @delcommand
print 'yes'
COMMIT TRANSACTION ada
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION ada
SELECT ERROR_Message() AS ErrorNumber;
END CATCH
end
COMMIT TRANSACTION Acbc
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION Acbc
END CATCH
END
【问题讨论】:
-
如果数据在文件中,为什么要使用 SQL Server 来实现这个目的?有很多更好的文件处理工具。
-
是否有必要在存储过程中完成整个 ETL 过程?这不是一种有效的做法。最好使用 SSIS 之类的东西,在其中加载文件,然后进行脚本组件转换,以利用 .NET 的正则表达式函数 (similar to this),然后加载到目标表中。
-
@iman,如果我的回答解决了您的问题,请点击投票柜台下方的接受检查接受它。 Please read this: someone-answers。谢谢!
标签: sql-server stored-procedures