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 |
ssunny
Posting Yak Master
133 Posts |
Posted - 2012-09-07 : 14:49:59
|
Hello Guys,Happy Friday. I was wondering if I can replace below cursor with CTE (or something else) which will be faster.--Table 1:test----------eid email1 a@a.com 2 b@a.com..........eid is an identity column.--Table 2:test1-------------id email1 a@a.com2 b@a.com3 c@a.com4 d@a.com.......... --querydeclare ecurs cursor for select email from test1 order by idopen ecurs declare @email varchar (200)fetch next from ecurs into @emailwhile @@FETCH_STATUS = 0beginif not exists (select eid from test where email = @email)insert into test (email) select @emailfetch next from ecurs into @emailendclose ecurs deallocate ecurs goI need to do this for lots of records and cursor is taking too long to complete.Thanks. |
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-09-07 : 14:59:14
|
You should be able to use either of the two queries below. If there are no duplicates in test1, you don't need the distinct keyword. It does not guarantee order of insertion though:-- 1INSERT INTO test( email )SELECT DISTINCT t1.emailFROM test1 t1WHERE t1.email NOT IN ( SELECT t.email FROM test t); -- 2 INSERT INTO test( email )SELECT DISTINCT t1.emailFROM test1 t1 LEFT JOIN test t ON t.email = t1.emailWHERE t1.email IS NULL; |
 |
|
ssunny
Posting Yak Master
133 Posts |
Posted - 2012-09-07 : 15:12:15
|
Thanks Sunita. Didn't think about this. I will let you know. |
 |
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-09-07 : 15:15:21
|
You are welcome (please test in dev before you apply it somewhere where it can cause damage). |
 |
|
ssunny
Posting Yak Master
133 Posts |
Posted - 2012-09-07 : 15:31:12
|
Too late. Production is my unit. Will let you know... |
 |
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-09-07 : 15:41:25
|
quote: Originally posted by ssunny Too late. Production is my unit. Will let you know...
omg! I don't wanna know!!! |
 |
|
ssunny
Posting Yak Master
133 Posts |
Posted - 2012-09-07 : 17:12:32
|
Your approach worked Sunita. Thank you very much. Have a good weekend. |
 |
|
|
|
|