[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

T-SQL to Update Table Dynamically

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

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 32

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 52

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

Survive A High-Traffic Event with Percona

Your application or website rely on your database to deliver information about products and services to your customers. You can’t afford to have your database lose performance, lose availability or become unresponsive – even for just a few minutes.

Question has a verified solution.

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

Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
When trying to connect from SSMS v17.x to a SQL Server Integration Services 2016 instance or previous version, you get the error “Connecting to the Integration Services service on the computer failed with the following error: 'The specified service …
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
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.

649 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