Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

update statment using function

$
0
0

Environment: Win7 and SQL server 2008 R2
Tools: SQL management tool 2008 R2

Problem: I have been trying to update id numbers in the staging table. T-SQL statement updates all id number in the staging table, but what if the we have multiple records for the same person who we are assigning the ID to his/her record. It should generate one pn_id per ssn regadless if there are several records for the same individual. for example, my code assigns the following id: 

Student table (ID, ssn, name, subject, grade, year)
(288258466,192160792 , Sally Johnson, Math, A, 2014 )
(176268917, 192160792, Sally Johnson, Spanish, B+, 2014 )
(900303787, 770616858, Jessica Simpson, Spanish, B, 2014 )
(704099635, 770616858, Jessica Simpson, IT, A, 2014 )
(704099640, 444718562, Douglas Mike, IT, A, 2014 )
(288258450, 31883459, Susan Jesson, IT, A, 2014 )
(176268960, 260518681, Veronica Floris, IT, A, 2014 )

The expected results should be as the following in the staging table
Student table (ID, ssn, name, subject, grade, year)
(288258466,192160792 , Sally Johnson, Math, A, 2014 )
(288258466, 192160792, Sally Johnson, Spanish, B+, 2014 )
(900303787, 770616858, Jessica Simpson, Spanish, B, 2014 )
(900303787, 770616858, Jessica Simpson, IT, A, 2014 )
(704099640, 444718562, Douglas Mike, IT, A, 2014 )
(288258450, 31883459, Susan Jesson, IT, A, 2014 )
(176268960, 260518681, Veronica Floris, IT, A, 2014 )

My code:

UPDATE a
SET pn_id =  (Select dbo.gen_id())
from  [dbo].[Staging_Table] a 
where SSN in (Select SSN from [dbo].[staging_Table]
group by SSN having count(SSN) > 1)
GO

I also tried the following code but no success

;with cte
As
(
Select	* , ROW_NUMBER() Over(Partition BY ssn Order by ssn)  As MyCount
from dbo.Staging_Table
)

Select * into #a from cte where MyCount=1


UPDATE a
SET pn_id =  (Select dbo.fn_gen_id())
from  staging_table a 
Full  join #a b on a.ssn = b.ssn

Drop table #a 
please help.


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>