Groups | Blog | Home
all groups > sql server programming > august 2003 >

sql server programming : Create default help


Hassan
8/12/2003 11:12:02 PM
I have a table as follows

Create table T1
( Col1 varchar(10),
Col2 numeric(18,1))

insert T1 ( Col1) values 'ABC123.4'
insert T1 ( Col1) values 'NAD'
insert T1 ( Col1) values 'XYZ'
insert T1 ( Col1) values 'ABC223.4'
insert T1 ( Col1) values 'ABC023.4'


What i want the output of T1 to look is as follows

Col1 Col2
ABC123.4 123.4
NAD null
XYZ null
ABC223.9 223.9
ABC023.5 23.5

Basically whenever i do an insert I want col2 to be updated with the
following logic

Case when Col1 not like 'ABC%' then null else cast(substring(col1,4,5) as
numeric(18,1)) end

Can i create a default with this and bind it to Col2 ? Or does it have to be
a trigger ? Please let me know how to write the TSQL

Thank you


sampangi
8/12/2003 11:30:57 PM
Please use computed column as shown

Create table T1
( Col1 varchar(10),
Col2 as Case when Col1 not like 'ABC%' then null else
cast(substring(col1,4,5) as
numeric(18,1)) end)

HTH,
Srinivas Sampangi


[quoted text, click to view]

oj
8/12/2003 11:57:07 PM
if you want to update the table...

--whole table
update T1
set col2=right(col1,len(col1)+1-nullif(patindex('%[0-9]%',col1),0))

--selective rows
update T1
set col2=right(col1,len(col1)+1-patindex('%[0-9]%',col1))
where patindex('%[0-9]%',col1)>0

instead you could create a computed column...

Create table T1
( Col1 varchar(10),
Col2 as case when patindex('%[0-9]%',col1)>0 then
right(col1,len(col1)+1-patindex('%[0-9]%',col1))
else null
end
)

--
-oj
RAC v2.2 & QALite!
http://www.rac4sql.net



[quoted text, click to view]

AddThis Social Bookmark Button