sql-server – 将值分配给变量的SELECT语句不能与数据检索操作结合使用

这个语句有什么问题?

ALTER Function [InvestmentReturn].[getSecurityMinLowForPeriod](@securityid int,
    @start datetime,
    @end datetime)
returns xml
begin

declare @results varchar(500)
declare @low int
declare @adjustedLow int
declare @day varchar(10)

if @end is null
begin
    set @end = getdate()
end
set @adjustedLow = (select min(adjLow) 
                        from (
                            select Low * [InvestmentReturn].[fn_getCorporateActionSplitFactor](isq.securityid, @start, convert(varchar,day, 111)) as adjLow 
                            from 
                                securityquote isq
                            where isq.securityid = @securityid and isq.day >= convert(varchar(10), @start, 111) and convert(varchar(10), @end, 111) >= isq.day
                            and low != -1 
                            ) as x)
select 
    top 1 @low = low
    , @day = day
    , @adjustedLow
--select high
from 
    securityquote sq
where 
    day >= convert(varchar(10), @start, 111) and convert(varchar(10), @end, 111) >= day
    and securityid = @securityid and low != -1
order by low asc

    set @results=  '<results type="debug_min">'
    set @results = @results + '<periodStart>' + coalesce(cast(@start as varchar(20)), 'NULL') + '</periodStart>' 
    set @results = @results + '<periodEnd>' + coalesce(cast(@end  as varchar(20)), 'NULL') + '</periodEnd>' 
    set @results = @results + '<securityID>' + coalesce(cast(@securityID as varchar(10)), 'NULL') + '</securityID>'
    set @results = @results + '<periodMin>' + coalesce(cast(@low as varchar(10)), '-11111') + '</periodMin>'
    set @results = @results + '<coraxAdjustedPeriodMin>' + coalesce(cast(@adjustedLow as varchar(10)), '-11111') + '</coraxAdjustedPeriodMin>'
    set @results = @results + '<dayMinOcurred>' + coalesce(@day, 'NULL') + '</dayMinOcurred>'
    set @results = @results + '</results>'

return @results

只是为了解释答案(在得到错误的原因后),我只是从第二个select语句中删除@adjustedLow。

来自SELECT语句的列值分配到@low和@day局部变量; @adjustedLow值不会分配到任何变量,它会导致问题:

问题在这里:

select 
    top 1 @low = low
    , @day = day
    , @adjustedLow  -- causes error!
--select high
from 
    securityquote sq
...

详细解释和解决方法:SQL Server Error Messages – Msg 141 – A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.

http://stackoverflow.com/questions/4608140/a-select-statement-that-assigns-a-value-to-a-variable-must-not-be-combined-with

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:sql-server – 将值分配给变量的SELECT语句不能与数据检索操作结合使用