?
Solved

T-SQL to Update Table Dynamically

Posted on 2016-10-06
5
Medium Priority
?
80 Views
Last Modified: 2016-10-06
Hi Experts,

I n step #2 In the following SP,  I tried to update the table called @AsIsTable but I keep getting this error:

Msg 1087, Level 16, State 1, Procedure sp_ImportingNewDump_1.0_Conslidated, Line 37 [Batch Start Line 0]
Must declare the table variable "@AsIsTable".


So how to fix that step?

CREATE PROCEDURE [dbo].[sp_ImportingNewDump_1.0_Conslidated]
	-- Add the parameters for the stored procedure here
	  @DumpDate nvarchar(255) = NULL
-----------------------------------------------------------------------------------------------------
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	DECLARE @AsIsTable varchar(MAX);
	DECLARE @CreateAsIsTableSQL varchar(MAX);
	DECLARE @VersionNumber nvarchar(255);
	DECLARE @VersionDate nvarchar(255);
	DECLARE @DataSourceName nvarchar(255);
	DECLARE @ImportingDate nvarchar(255);

	SET NOCOUNT ON;
BEGIN TRAN
BEGIN TRY  
 -----------------------------------------------------------------------------------------------------
 -- 1. Create AsIs Table
	SET @AsIsTable = N'tb_Test_Services_ImportedByWizard_AsIs_'+@DumpDate+''
	 IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @AsIsTable)
       PRINT 'Table '  + @AsIsTable + ' already exist'
    ELSE 
		SET @CreateAsIsTableSQL = 'CREATE TABLE ' + @AsIsTable + ' (
		[AgencyName] [nvarchar](255) NULL,
		[ImportingDate] [nvarchar](255) NULL,
		[VersionNumber] [nvarchar](50) NULL,
		[VersionDate] [nvarchar](255) NULL,
		[DataSourceName] [nvarchar](255) NULL,
		) ON [PRIMARY]';

Execute (@CreateAsIsTableSQL);
-----------------------------------------------------------------------------------------------------
  -- 2. Update AsIs Table
UPDATE @AsIsTable
    SET 
	   VersionNumber = @VersionNumber
      ,VersionDate = @VersionDate
      ,DataSourceName = @DataSourceName
	  ,ImportingDate = @ImportingDate

-----------------------------------------------------------------------------------------------------
END TRY

BEGIN CATCH  
    SELECT   
        ERROR_NUMBER() AS ErrorNumber  
        ,ERROR_SEVERITY() AS ErrorSeverity  
        ,ERROR_STATE() AS ErrorState  
        ,ERROR_PROCEDURE() AS ErrorProcedure  
        ,ERROR_LINE() AS ErrorLine  
        ,ERROR_MESSAGE() AS ErrorMessage;  
  
    IF @@TRANCOUNT > 0  
        ROLLBACK TRANSACTION;  
END CATCH;  

IF @@TRANCOUNT > 0  
    COMMIT TRANSACTION;  
-----------------------------------------------------------------------------------------------------
END

Open in new window


Thanks a lot in advance.
Harreni
0
Comment
Question by:Harreni
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 70

Assisted Solution

by:Éric Moreau
Éric Moreau earned 500 total points
ID: 41831634
you need to create dynamic SQL (build a string of your query and execute it) to do that. Have a look at http://www.codeproject.com/Articles/20815/Building-Dynamic-SQL-In-a-Stored-Procedure
0
 
LVL 51

Accepted Solution

by:
Vitor Montalvão earned 1000 total points
ID: 41831638
You can't use a variable directly in an UPDATE command. You need to use a similar solution as you used for step 1:
DECLARE @UpdateCmd VARCHAR(MAX)

SET @UpdateCmd = 'UPDATE ' + @AsIsTable + 
		' SET VersionNumber = ' + @VersionNumber
			',VersionDate = ' + @VersionDate
			',DataSourceName = ' + @DataSourceName
			',ImportingDate = ' + @ImportingDate

EXECUTE(@UpdateCmd)

Open in new window

NOTE: You may need to convert some of the variables to get the correct data type.
0
 
LVL 29

Assisted Solution

by:Pawan Kumar
Pawan Kumar earned 500 total points
ID: 41831706
@Vitor sir - You missed few + after variables..

@Author - Changed entire code for you..

One more thing if table exists then we should update the data. If table doesnot exists then just create table and insert data.

As of now i have not added code for Insert data - let me know if you want to insert row in case of new table creation.


CREATE PROCEDURE [dbo].[sp_ImportingNewDump_1.0_Conslidated]
	-- Add the parameters for the stored procedure here
	  @DumpDate nvarchar(255) = NULL
-----------------------------------------------------------------------------------------------------
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	DECLARE @AsIsTable varchar(MAX);
	DECLARE @CreateAsIsTableSQL varchar(MAX);
	DECLARE @VersionNumber nvarchar(255);
	DECLARE @VersionDate nvarchar(255);
	DECLARE @DataSourceName nvarchar(255);
	DECLARE @ImportingDate nvarchar(255);
	DECLARE @UpdateCmd VARCHAR(MAX);

	SET NOCOUNT ON;
BEGIN TRAN
BEGIN TRY  
 -----------------------------------------------------------------------------------------------------
 -- 1. Create AsIs Table
	SET @AsIsTable = N'tb_Test_Services_ImportedByWizard_AsIs_'+@DumpDate+''
	 IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @AsIsTable)
       
	 BEGIN   
	   
	    PRINT 'Table '  + @AsIsTable + ' already exist'	   

		SET @UpdateCmd = 'UPDATE ' + @AsIsTable + 
						' SET VersionNumber = ' + @VersionNumber +
						',VersionDate = ' + @VersionDate +
						',DataSourceName = ' + @DataSourceName +
						',ImportingDate = ' + @ImportingDate

		EXECUTE(@UpdateCmd)

	END
    ELSE 
	BEGIN

		SET @CreateAsIsTableSQL = 'CREATE TABLE ' + @AsIsTable + ' (
		[AgencyName] [nvarchar](255) NULL,
		[ImportingDate] [nvarchar](255) NULL,
		[VersionNumber] [nvarchar](50) NULL,
		[VersionDate] [nvarchar](255) NULL,
		[DataSourceName] [nvarchar](255) NULL,
		) ON [PRIMARY]';

		Execute (@CreateAsIsTableSQL);
	END

END TRY

BEGIN CATCH  
    SELECT   
        ERROR_NUMBER() AS ErrorNumber  
        ,ERROR_SEVERITY() AS ErrorSeverity  
        ,ERROR_STATE() AS ErrorState  
        ,ERROR_PROCEDURE() AS ErrorProcedure  
        ,ERROR_LINE() AS ErrorLine  
        ,ERROR_MESSAGE() AS ErrorMessage;  
  
    IF @@TRANCOUNT > 0  
        ROLLBACK TRANSACTION;  
END CATCH;  

IF @@TRANCOUNT > 0  
    COMMIT TRANSACTION;  

END

-

Open in new window


Enjoy !!
0
 
LVL 51

Expert Comment

by:Vitor Montalvão
ID: 41831708
Yes, some plus sign missed (didn't tested, that's why). Thanks for the call of attention:
DECLARE @UpdateCmd VARCHAR(MAX)

SET @UpdateCmd = 'UPDATE ' + @AsIsTable + 
		' SET VersionNumber = ' + @VersionNumber +
			',VersionDate = ' + @VersionDate +
			',DataSourceName = ' + @DataSourceName +
			',ImportingDate = ' + @ImportingDate

EXECUTE(@UpdateCmd)

Open in new window

1
 

Author Closing Comment

by:Harreni
ID: 41831714
Thanks a lot experts for your fast response and explanation.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question