我正在使用下面的存储过程上传文件到一个数据库,其中每个文件都有一个对应表,但有时候表不存在,在这种情况下,我想将文件名添加到名为NewTables.I无法获得存储过程语法工作有人可以帮助我。我相信错误是在我检查表中存在不正确的存储过程语法
ALTER proc [dbo].[UploadCSVFiles]
@FilePath varchar(100) ,
@FileName varchar(100),
@TableName varchar(250)
AS
BEGIN
DECLARE @SqlStmt nvarchar(max)
DECLARE @ErrorCode int
SET @SqlStmt='Truncate table dbo.[' + @TableName +']'
EXEC(@SqlStmt);
set @SqlStmt =N'
IF not EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].['[email protected] +N']'') AND type in (N''U''))
BEGIN
INSERT INTO dbo.NewTables ('[email protected]+N','[email protected]+N') Values('[email protected]+N','[email protected]+N')
END
ELSE
BEGIN
INSERT INTO '[email protected]+N'
select *
from openrowset(''MSDASQL''
,''Driver={Microsoft Access Text Driver (*.txt, *.csv)};
DefaultDir='[email protected]+N'''
,''select * from "'[email protected]+N'"'')
END
'
EXEC(@SqlStmt);
感谢 饶
感谢fpop和Christine第一部分,我已经提出了你的建议,但仍然出现错误
Msg 4701, Level 16, State 1, Line 1
Cannot find the object "Customer" because it does not exist or you do not have permissions.
看来如果语句不插入新表
这里是最后的版本
USE [MyDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[UploadFiles_2]
@FilePath varchar(100) ,
@FileName varchar(100),
@TableName varchar(250)
AS
BEGIN
DECLARE @SqlStmt nvarchar(max)
DECLARE @ErrorCode int
SET @SqlStmt='Truncate table dbo.[' + @TableName +']'
EXEC sp_executesql @SqlStmt;
set @SqlStmt =N'
IF (NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].['[email protected] +N']'') AND type in (N''U''))
BEGIN
INSERT INTO dbo.NewTables (TableName,FileName) Values('''[email protected]+N''','''[email protected]+N''')
END
ELSE
BEGIN
INSERT INTO '[email protected]+N'
select *
from openrowset(''MSDASQL''
,''Driver={Microsoft Access Text Driver (*.txt, *.csv)};
DefaultDir='[email protected]+N'''
,''select * from "'[email protected]+N'"'')
END'
EXEC sp_executesql @SqlStmt;
END
嗨之前就存在,你有,你可以发布一个错误? – edge2