Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
dvadithala
Starting Member
1 Post |
Posted - 2009-11-19 : 16:37:53
|
| Hi there,I am new SQL Server and I was given a task to write a simple Stored Procedure. Requirement is to lookup the column name dynamically and update the rows based on the condition. I had started to create my first stored procedure (never written one!!!). So I wanted to if this correct approach or is there a simpler and effective way to wrie the Proc. Any suggestions will be great help. Many thanks to all of you.____________________________________________________________________Here is the procedure (which I am trying):USE [testdb]GO/****** Object: StoredProcedure [dbo].[usp_Recode_Same_Variables] Script Date: 11/19/2009 19:05:20 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER procedure [dbo].[usp_Recode_Same_Variables] -- creating/ altering the procedure@Project_Name varchar(120),@Survey_Name varchar(120) = 'Survey',@Outcome_Column varchar(50) = 'completed',@Old_Column_Name varchar(10), -- declaring input parameters@New_Column_Name varchar(10), @New_Values int,@Old_Values int,@Recode_Type varchar(50) As Begin Tran Recoding_New_Column -- Beginning the transactiondeclare @Mycommand nvarchar(50) -- declaring the variablesdeclare @Newquestion nvarchar(50)declare @Oldquestion nvarchar(50)declare @mynewvalues varchar(10)declare @myoldvalues varchar(10)declare @ProjectName varchar(120)declare @mysql nvarchar(500)declare @survey varchar(120)declare @outcome varchar(50)declare @recodetype varchar(50) Set @Mycommand = 'Update Test_data set ' -- setting/Initializing the variablesset @Newquestion = @New_Column_Nameset @Oldquestion = @Old_Column_NameSet @mynewvalues = @New_ValuesSet @myoldvalues = @Old_ValuesSet @ProjectName = @Project_Nameset @survey = @Survey_Nameset @outcome = @Outcome_Columnset @recodetype = @recode_typeIF @Recode_Type = 'Single'Begin IF @myoldvalues is null -- Checks the condition if the old values contains null set @mysql = @mycommand + @Newquestion + '=' + @mynewvalues + 'where ' + @Oldquestion + ' is null' + ' and ' + @Survey + ' = '''+ @ProjectName + '''' + ' and ' + 'Outcome' + ' = '''+ @Outcome + '''' -- Executes the statement if the old values are null Else set @mysql = @mycommand + @Newquestion + '=' + @mynewvalues + 'where ' + @Oldquestion + '=' + @Myoldvalues + ' and ' + @Survey + ' = '''+ @ProjectName + '''' + ' and ' + 'Outcome' + ' = '''+ @Outcome + '''' -- Executes the statement if the old values are not nullEndExec (@Mysql) -- Executes the batch of statementsCommit Tran Recoding_New_Column -- committing the transaction and updating the valuesesCheers - DV |
|
|
X002548
Not Just a Number
15586 Posts |
|
|
|
|
|