Sunday, February 19, 2012

Help request with UPDATE/CASE

Hi,

I have a table as follows:

CREATE TABLE [MyTable] (
[SaleYear] [smallint] ,
[SaleMonthNum] [smallint] ,
[SaleMonthName] [nvarchar] (20) ,
[TotalSale] [money] NULL
) ON [PRIMARY]
GO

What I want is to update the field 'SaleMonthName' based on the 'SaleMonthNum' field using the CASE expression. I want something like this (pseudo-code):

update Mytable
set SaleMonthName
Case:
IF SaleMonthNum =1, then := 'January'
IF SaleMonthNum =2, then := 'February'
...
IF SaleMonthNum =12, then := 'December'

Many TIA.update Mytable
set SaleMonthName = case when salemonthnum =1 then 'jan'
when salemonthnum =2 then 'feb'
when salemonthnum =3 then 'march'
.....
else '??' end|||= case SaleMonthNum when 1 then 'January' when ... else '' end
SQL Server 2000 Books Online (Updated 2004) (http://www.microsoft.com/sql/techinfo/productdoc/2000/books.asp)|||declare @.MonthName varchar(20)
set @.MonthName = 'March'
select month(cast(@.MonthName + ' 1, 2004' as datetime))|||Granted that I'm a lazy bum, but I'd use:update Mytable
set SaleMonthName = DateName(month, DateAdd(month, [SaleMonthNum], '2000-12-01'))-PatP|||Oops. Looks like I had the conversion requirements back asswards.

Lazy is good! A busy DBA is a bad DBA.|||Thanks all. Many thanks :)

No comments:

Post a Comment