0

I was wondering if you could tell me what is wrong with my query?

The parameter @TableName is an input parameter.

Why do I have to declare it again?

CREATE PROCEDURE [dbo].[OpenExcel]
 @FileName nvarchar(2000),
 @TableName varchar(2000)
AS
 BEGIN
 DECLARE @Provider nvarchar(2000)
 SET @Provider = 'Microsoft.ACE.OLEDB.12.0'
 DECLARE @etValue nvarchar(4000)
 SET @RetValue = 'select * 
 from openrowset(''' + @Provider + 
 ''',''Excel 8.0;Database=' + 
 @FileName + ';hdr=no' + ''',
 ''select " from [Sheet1$]'' )'
 DELETE FROM @TableName
 INSERT INTO @TableName
 EXEC(@RetValue)
 END

An image of the stored procedure

The error message I receive is:

Msg 1087, Level 16, State 1, Procedure OpenExcel, Line 26
Must declare the table variable "@TableName".

Well I'm trying to pass the Excel path (@FileName) and table name (@TableName; in which the data should be inserted) to the stored procedure.

How can I achieve that?

I have different tables with different structures. Please help me with this issue.

John K. N.
18.9k14 gold badges56 silver badges117 bronze badges
asked Sep 29, 2018 at 7:11

1 Answer 1

0

Here is your solution:

Create Procedure [dbo].[OpenExcel]
 @FileName nvarchar(2000),
 @TableName varchar(2000) 
AS Begin 
 declare @Provider nvarchar(2000);
 set @Provider = 'Microsoft.ACE.OLEDB.12.0';
 declare @RetValue nvarchar(4000) ;
 set @RetValue='select * from openrowset("' + @Provider + ''',''Excel 8.0;Database=' + @FileName +';hdr=no'+''', ''select * from [Sheet1$]" )' 
 declare @Bufr nvarchar(4000) 
 set @Bufr='delete from '+@TableName+';'
 set @Bufr=@Bufr+'insert into '+@TableName exec(@RetValue) 
End 
Glorfindel
2,2075 gold badges19 silver badges26 bronze badges
answered Sep 29, 2018 at 8:57
2
  • thank you very much . the problem is that I can see the results but not in the destination table. would you mind if you test it yourself ? I can see the result of the procedure but the data won't be inserted into the destination table. Commented Sep 29, 2018 at 9:45
  • DECLARE @Bufr nvarchar(4000) --SET @Bufr='delete from '+@TableName+';' SET @Bufr='insert into '+@TableName + 'EXEC(@RetValue) ' EXEC (@Bufr) we have to change it this way . but this one won't work either !!! you know.. the insert part won't be executed we have to solve this issue Commented Sep 29, 2018 at 9:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.