我正在使用下面的存儲過程上傳文件到一個數據庫,其中每個文件都有一個對應表,但有時候表不存在,在這種情況下,我想將文件名添加到名爲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