Solved

T-SQL to Update Table Dynamically

Posted on 2016-10-06
5
33 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 69

Assisted Solution

by:Éric Moreau
Éric Moreau earned 125 total points
Comment Utility
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 45

Accepted Solution

by:
Vitor Montalvão earned 250 total points
Comment Utility
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 17

Assisted Solution

by:Pawan Kumar Khowal
Pawan Kumar Khowal earned 125 total points
Comment Utility
@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 45

Expert Comment

by:Vitor Montalvão
Comment Utility
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
Comment Utility
Thanks a lot experts for your fast response and explanation.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
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.

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now