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 |
arkiboys
Master Smack Fu Yak Hacker
1433 Posts |
Posted - 2011-01-14 : 06:38:55
|
Hi,tblMain has three fields. ID, Field2, field3After several inserts into tblMain, it has duplicate rows.I am trying to delete the extra row using row_number() as follows but the error I get is:invalid object name 'CTE tblResult'; with [CTE tblResult]as(select RowNum = row_number() over (partitioin by ID, order by ID), field2, field3from tblMain)delete from [CTE tblResult] where RowNum > 1delete tblMaininsert into tblMainselect * from [CTE tblResult]Any thoughts on what I am doing wrong please?Thanks |
|
dataguru1971
Master Smack Fu Yak Hacker
1464 Posts |
Posted - 2011-01-14 : 06:42:09
|
You can't use a CTE like that but you can use a physical temp table do the same.selectRowNum = row_number() over (partitioin by ID, order by ID),field2,field3INTO #tempfromtblMainDelete from #temp where RowNum >1TRUNCATE TABLE tblMaininsert into tblMainSelect * From #temp Poor planning on your part does not constitute an emergency on my part. |
 |
|
webfred
Master Smack Fu Yak Hacker
8781 Posts |
Posted - 2011-01-14 : 07:34:30
|
You can directly delete the dups like this:delete dtfrom(selectRowNum = row_number() over (partition by ID, order by ID),field2,field3fromtblMain) as dtwhere RowNum > 1 No, you're never too old to Yak'n'Roll if you're too young to die. |
 |
|
Sachin.Nand
2937 Posts |
Posted - 2011-01-14 : 08:26:06
|
quote: ; with [CTE tblResult]as(selectRowNum = row_number() over (partitioin by ID, order by ID),field2,field3fromtblMain)delete from [CTE tblResult] where RowNum > 1
Deleting from [CTE tblResult] is actually going to delete from tblmain.So just put an insert clause after the query I have quoted.This will suffice your requirement.PBUH |
 |
|
arkiboys
Master Smack Fu Yak Hacker
1433 Posts |
Posted - 2011-01-14 : 09:10:59
|
Thank you all. |
 |
|
|
|
|
|
|