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 |
ham_tim_hieu
Starting Member
4 Posts |
Posted - 2007-02-24 : 11:26:28
|
I have a Table, example Table1Col1 Col2a aab bbc ccNow I want to creat a Table Views, that have content the same as Table1 includes Sequence column, example View1Seq Col1 Col21 a aa2 b bb3 c ccHow should I do, thanks |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-02-24 : 19:02:57
|
[code]select Seq = (select count(*) from table x where x.col1 <= t.col1) col1, col2from table t[/code] KH |
 |
|
ham_tim_hieu
Starting Member
4 Posts |
Posted - 2007-02-24 : 23:20:48
|
Dear KH, I understand your idea, thanksTable1 that I show in that question is just only for example. But in fact, Table1 is not a real Table, it is a result of very complex query: SELECT ... FROM .. WHERE ... GROUP BY ... HAVING ... ORDER BY....., if I do as your ideaselect Seq = (select count(*) from (SELECT ... FROM .. WHERE ... GROUP BY ... HAVING ... ORDER BY.....) as x where x.col1 <= t.col1) col1, col2from (SELECT ... FROM .. WHERE ... GROUP BY ... HAVING ... ORDER BY.....) as tSo I have to run this complex query twice, it may take slowly, not optimizedShould you have another better way?Thanks |
 |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-02-25 : 02:31:47
|
"Should you have another better way?"Yes. Don't do it in SQL. Do it in your front end application where you present the data KH |
 |
|
ham_tim_hieu
Starting Member
4 Posts |
Posted - 2007-02-25 : 03:56:23
|
I have an idea, I use Stored Procedures instead of Table ViewIn my SP, I creat a temporary table, and I insert query result to this table, then I execute your sql with temporary tableIt is optimized? (I prefer do in Database than in Application)Thanks |
 |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-02-25 : 04:44:31
|
The best option is still to do it in Application. It will be only one single select compare to an insert & a select (insert into temp table and then select from the temp table) if you do it in the stored procedure. Depending on the number of rows return and the complication of the query, the Stored Procedure way might not be efficient."I prefer do in Database than in Application"Even if doing it in Application is much easier and faster than doing it in Database ? If you absolutely had to do it in database, create the temp table with the seq as identity column. KH |
 |
|
ham_tim_hieu
Starting Member
4 Posts |
Posted - 2007-02-25 : 06:58:05
|
OK, I use "create the temp table with the seq as identity column" because even my query is complex but it didn't return many rows in result |
 |
|
|
|
|
|
|