Sunday, February 26, 2012

dynamic update

i have a table with the following values

iden nam status
-- -- --
1 pp NULL
1 kk NULL
2 rr NULL
2 nn NULL
2 jj NULL
3 hh NULL

now i want to update the status cloumn in this table in such a way that the status colum = 'Status is' + iden + nam for all distinct values of iden from the table

how can we do this without using a cursor?

Here it is,

Code Snippet

Create Table #data (

[iden] int ,

[nam] Varchar(100) ,

[status] Varchar(100)

);

Insert Into #data Values('1','pp',NULL);

Insert Into #data Values('1','kk',NULL);

Insert Into #data Values('2','rr',NULL);

Insert Into #data Values('2','nn',NULL);

Insert Into #data Values('2','jj',NULL);

Insert Into #data Values('3','hh',NULL);

Update #data

Set

[status] = 'Status is ' + Cast(iden as varchar) + ' ' +nam

Select * from #data

|||

The most important question is why would you want to do that? It is both unnecessary, and not a good design consideration to store data that is easily 'computed' from existing row data.

Use a VIEW instead.

CREATE VIEW dbo.vMyTableView

AS

SELECT

Iden,

Nam,

[Status] = 'Status is ' + Cast( Iden as varchar(10) ) + Nam

FROM dbo.MyTable

GO

No comments:

Post a Comment