开发者

Weird SQL Server behavior

What´s the name of the behavior in the statement below?

Create table dbo.Foo(name varchar(10))

insert dbo.Foo (name)
select 'Weird'
union
select 开发者_StackOverflow'SQL'
union
select 'Server'
union
select 'behavior'

declare @title varchar(max)
set @title = ''
select @title = name + ' ' + @title from dbo.Foo

select @title

--returns 'Weird SQL Server behavior'

This can also be done with integers. I want to know the name for this behavior, that mix scalar and set operations.


What exactly is weird about this? You select 4 rows, SQL Server runs:

 @title = name + ' ' + @title

Four times, and you end up with the string you mention.

Kinda lucky too, since the ordering is really random.


String concatenation?


What´s the name of the behavior in the statement below?

I would call that a side effect from evaluating an expression for each row of a query.


This is one of the methods used sometimes to aggregate strings in SQL, see Concatenating Row Values in Transact-SQL. Is no recommended because it relies on order of execution. On a real table ou can get 'Weird SQL Behavior' but also 'Behavior Weird Server SQL'. The problem is documented in PRB: Execution Plan and Results of Aggregate Concatenation Queries Depend Upon Expression Location.


Nobody mentioned that SELECT @title = name FROM dbo.Foo is the easier way to pick a value from a table and put it in a variable inside a SQL BATCH.

So, select @title = name + ' ' + @title from dbo.Foo picks the value of each row in dbo.Foo and add it in the end of @title.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜