Pages

Aug 5, 2010

How to use dynamic column name in update query + SQL SERVER

This is a General Requirement that we may be in a need to update 
the table using a dynamic column name.
Say for Eg:
Here my case is ,
I need to update a table, when user reaches different stage of the Ordering Proces.
So i have columns as name, age, stage1,stage2,stage3 etc upto 8 stages.
When user enter each stage i will be calling this procedure with stage 
as parameter like 1,2,3 etc.. up to 8.

CREATE PROCEDURE [dbo].[UserTracking_usp]
(       
      @TrackID int
      @Stage varchar(10)
)
AS

BEGIN
            // to store dynamic column name
            DECLARE @CurrentStage varchar(50)
            DECLARE @UpdateSQL varchar(200)

            SET @CurrentStage =
            CASE 
                  WHEN @Stage='2'  THEN  'Stage2'
                  WHEN @Stage='3'  THEN  'Stage3'
                  WHEN @Stage='4'  THEN  'Stage4'
                  WHEN @Stage='5'  THEN  'Stage5'
                  WHEN @Stage='6'  THEN  'Stage6'
                  WHEN @Stage='7'  THEN  'Stage7'
                  WHEN @Stage='8'  THEN  'Stage8'
            END
       SET  @UpdateSQL = 
       'UPDATE User_Tracking SET ' + convert(varchar, @CurrentStage) + '= 1   
       WHERE
       User_Tracking_ID = ' + convert(varchar, @TrackID);
       EXEC (@UpdateSQL)
       END    


So this procedure will examine which column name should be updated
using a case statement and substitute as a dynamic column name for 
update query as shown above.


In the same way one can use for select,delete statements etc..

1 comment:

Anonymous said...

SELECT * INTO dbo.sTemp
FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\test.xls;IMEX=1',
'SELECT * FROM [Sheet2$]')


GO


UPDATE INV
SET
INV.HardwareMaintenanceEndDate = TMP.MostRecentDate
FROM
dbo.Inventory as INV
INNER JOIN
(
SELECT
Inventoryid,
CASE
WHEN ISNULL([Warranty End Date],'') >= ISNULL([Maint End Date - HP Maint],'')
THEN
[Warranty End Date]
ELSE
[Maint End Date - HP Maint]
END
AS MostRecentDate,
[Warranty End Date],
[Maint End Date - HP Maint]
FROM sTemp
) TMP
ON
TMP.Inventoryid = INV.InventoryID

GO

DROP TAble stemp

GO