Solved

T-SQL to Update Table Dynamically

Posted on 2016-10-06
5
62 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 125 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 49

Accepted Solution

by:
Vitor Montalvão earned 250 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 28

Assisted Solution

by:Pawan Kumar
Pawan Kumar earned 125 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 49

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

Independent Software Vendors: 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

Suggested Solutions

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

726 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