Friday, March 9, 2012

Is it necessary to order again?

I have a function that returns a table:

CREATE FUNCTION dbo.Example(@.Param int)
RETURNS @.Tbl TABLE (
Field1 int,
Field2 int) AS
BEGIN
INSERT @.Tbl (Field1,Field2)
SELECT FieldA,FieldB FROM DataTable
WHERE FieldC = @.Param
ORDER BY FieldA
RETURN
END

The statement that populates the table orders the data. In order
to ensure the results are ordered that way, should the call to the
function include an ordering? I.e., is this sufficient

SELECT * FROM dbo.Example(17)

or is this necessary? --

SELECT * FROM dbo.Example(17) ORDER BY Field1

Thanks!"Jim Geissman" <jim_geissman@.countrywide.com> wrote in message
news:b84bf9dc.0408051457.6ae418c0@.posting.google.c om...
> I have a function that returns a table:
> CREATE FUNCTION dbo.Example(@.Param int)
> RETURNS @.Tbl TABLE (
> Field1 int,
> Field2 int) AS
> BEGIN
> INSERT @.Tbl (Field1,Field2)
> SELECT FieldA,FieldB FROM DataTable
> WHERE FieldC = @.Param
> ORDER BY FieldA
> RETURN
> END
> The statement that populates the table orders the data.

No, it doesn't. Tables are sets of data. They have no order.

Now, your statement may put the data into the table in order... but there's
no guarantee that SQL Server will store it in that order.

> In order
> to ensure the results are ordered that way, should the call to the
> function include an ordering? I.e., is this sufficient
> SELECT * FROM dbo.Example(17)
No

> or is this necessary? --
> SELECT * FROM dbo.Example(17) ORDER BY Field1

Yes.

> Thanks!

No comments:

Post a Comment