[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

T-SQL to Update Table Dynamically

Posted on 2016-10-06
5
Medium Priority
?
93 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
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 53

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 37

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 53

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

I have a large data set and a SSIS package. How can I load this file in multi threading?
Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
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.
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…
Suggested Courses

873 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