请检查此查询:
declare @T table
(
FirstColumn datetime primary key,
S_E1 float
)
insert into @T(FirstColumn, S_E1) values
('2012-01-01T00:00:01', 1),
('2012-01-01T00:00:02', 2),
('2012-01-01T00:00:03', 3),
('2012-01-01T00:00:04', 4),
('2012-01-01T00:00:05', 5),
('2012-01-01T00:00:06', 6)
declare @Take varchar = '1'
declare @StartDate varchar(10)='2012-01-01T00:00:01'
declare @EndDate varchar(10) = '2012-01-01T00:00:06'
declare @count varchar(Max)
DECLARE @SQL nvarchar(Max)
set @count = (select count(FirstColumn) from @T Where FirstColumn Between ''+@StartDate+'' and ''+@EndDate+'')
set @SQL =' select S_E1 from @T where S_E1 ='+ @Take+''
BEGIN try
while(CAST(@Take AS int) < CAST(@count AS int))
Begin
print @SQL;
set @Take = CONVERT(varchar,CAST(@Take AS int)+1)
end
END TRY
BEGIN CATCH
select ERROR_MESSAGE() as errormessage
END CATCH
问题: 在上面的查询中,我无法更新@Take变量值。请让我知道我在哪里走错路。
答案 0 :(得分:1)
更改了一些数据类型并将@SQL的赋值移到了循环中。
declare @T table
(
FirstColumn datetime primary key,
S_E1 float
)
insert into @T(FirstColumn, S_E1) values
('2012-01-01T00:00:01', 1),
('2012-01-01T00:00:02', 2),
('2012-01-01T00:00:03', 3),
('2012-01-01T00:00:04', 4),
('2012-01-01T00:00:05', 5),
('2012-01-01T00:00:06', 6)
declare @Take int = 1
declare @StartDate datetime = '2012-01-01T00:00:01'
declare @EndDate datetime = '2012-01-01T00:00:06'
declare @count int
declare @SQL nvarchar(Max)
set @count = (select count(FirstColumn)
from @T
where FirstColumn Between @StartDate and @EndDate)
begin try
while @Take <= @count
begin
set @SQL =' select S_E1 from @T where S_E1 ='+ cast(@Take as varchar(10))+''
print @SQL;
set @Take = @Take + 1
end
end try
begin catch
select error_message() as errormessage
end catch