j_*********@hotmail.com (Jim Lewis) wrote in
news:78**************************@posting.google.c om:
I started writing code to determine which was the more efficient
approach and I encountered something interesting
CREATE TABLE TestLoop (
TestLoopID int IDENTITY (1, 1) NOT NULL ,
FirstName varchar(50) NULL)
INSERT INTO TestLoop (FirstName) VALUES ('Tom')
INSERT INTO TestLoop (FirstName) VALUES ('Dick')
INSERT INTO TestLoop (FirstName) VALUES ('Harry')
DECLARE @OutPut as Vachar(8000)
SET @OutPut = ''
SELECT @OutPut = @OutPut + FirstName FROM TestLoop
From what you've written so far, I don't think ANYTHING would be *output*.
If you added
SELECT @OutPut
as a command after the above, I would expect this result
TomDickHarry
--Output Tom, Dick, Harry,
I do not know that T-SQL would flatten all the values into the string.
There is no need for looping at all! How and why does SQL Server do
this?
Next, the truth is that the result is undefined because there is no
telling what order the optimizer will choose to return the results in.
E.g., if you happened to have created an index on FirstName, the optimizer
might very well decide that the index was the quickest way to get the
field values - and since you did not specify an ORDER BY Clause, you might
well get this output:
DickHarryTom
However, in controlled situations, this sort of shenanigans will generally
function as required. A great many cursors can be eliminated with
cleverness of this sort - but don't tell Mama.
--
Ross Presser -- rpresser AT imtek DOT com
"... VB is essentially the modern equivalent of vulgar Latin in 13th
Centurary Europe. Understand it, and you can travel to places you never
heard of and still understand some people." -- Alex K. Angelopoulos