September 10, 2010 at 5:53 am
Hi,
I have test database with following script. I am trying to explain my problem with this sample db script. I am creating a temp. table with the ordered column from other table and then using that table to join the other table. If you notice the output of the below select query, the returned rows from first table are in the sequence of insertion not in the sequence of the temp. table.
Is there any other way to retrieve rows in the sequence of temp. (joined) table?
CREATE TABLE [dbo].[Table_2](
[c1] [int] NULL,
[c2] [nvarchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Table_2] ([c1], [c2]) VALUES (1, N'z')
INSERT [dbo].[Table_2] ([c1], [c2]) VALUES (2, N'y')
INSERT [dbo].[Table_2] ([c1], [c2]) VALUES (3, N'x')
INSERT [dbo].[Table_2] ([c1], [c2]) VALUES (4, N'a')
INSERT [dbo].[Table_2] ([c1], [c2]) VALUES (5, N'b')
INSERT [dbo].[Table_2] ([c1], [c2]) VALUES (6, N'c')
CREATE TABLE [dbo].[Table_1](
[c1] [int] NULL,
[c2] [nvarchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Table_1] ([c1], [c2]) VALUES (3, N'x')
INSERT [dbo].[Table_1] ([c1], [c2]) VALUES (2, N'y')
INSERT [dbo].[Table_1] ([c1], [c2]) VALUES (1, N'z')
INSERT [dbo].[Table_1] ([c1], [c2]) VALUES (6, N'c')
INSERT [dbo].[Table_1] ([c1], [c2]) VALUES (5, N'b')
INSERT [dbo].[Table_1] ([c1], [c2]) VALUES (4, N'a')
----------------------------------------------------
IF OBJECT_ID('TempDB..#tblTemp','U') IS NOT NULL
DROP TABLE #tblTemp
CREATE TABLE #tblTemp (Id int);
INSERT INTO #tblTemp SELECT c1 FROM Table_2 ORDER BY c2
SELECT *
FROM Table_1
INNER JOIN #tblTemp ON Id=Table_1.c1
DROP TABLE #tblTemp
Regards,
Jigs
September 10, 2010 at 6:15 am
If you want to retrieve rows in a particular order, you must put an ORDER BY on the statement that retrieves the data with the appropriate columns listed
An order by on the insert only affects identity columns (if present). It does not guarantee the order that data will be returned from that table
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
September 10, 2010 at 6:16 am
There is no guarantee that rows will be returned in any particular unless ORDER BY is specified.
There is also no guarantee that rows will be inserted in a particular order, even if the inserts are sourced as SELECT...ORDER BY...
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply