学习动态SQL

时间:2016-07-10 13:35:31

标签: sql loops dynamic

我正在尝试学习动态SQL

我已经设置了一个基本的例子,我被卡住了,我不明白为什么@Month变量不会随每个循环更新。

以下是我做的例子:

declare @M int = 1
declare @SQL varchar(max) = ''
declare @Cnt int = 1
declare @Month varchar(25) = (datename(m, '2016-' + convert(varchar(2), @M) + '-01'))

while @Cnt <= 12
begin
    set @SQL = @SQL + 'select ' + convert(varchar(25), @M) + ' as M, ''' + @Month + ''' as Month'
    if  @Cnt <> 12 set @SQL = @SQL + ' Union All '  
    set @Cnt = @Cnt + 1
    set @M = @M + 1
end

 exec  (@SQL)

结果:

M   Month
1   January
2   January
3   January
4   January
5   January
6   January
7   January
8   January
9   January
10  January
11  January
12  January

我希望从1月到12月生成MonthName

为什么月份名称不会更新每个循环? 让我发疯,我等不及明天上班才能问我的老板。今晚需要睡觉。

非常感谢。

3 个答案:

答案 0 :(得分:0)

每次循环时都需要添加日期,就像@M变量一样。拿另一个变量作为日期。

DECLARE @SQL varchar(max) = ''
DECLARE @Cnt int = 1
DECLARE @TempDate DateTime = Cast('2016-03-01' As DateTime)

然后在while循环中添加月份

WHILE @Cnt <= 12
BEGIN
    set @SQL = @SQL + 'select ' + CAST(MONTH(@TempDate) AS VARCHAR(2)) + ' as M, ''' + DateName(m,@TempDate) + ''' as Month '
    IF  @Cnt <> 12 SET @SQL = @SQL + ' Union All ' 
    SET @TempDate = DateAdd(m, @Cnt, @TempDate)
    SET @Cnt = @Cnt +1
END

EXEC  (@SQL)

答案 1 :(得分:0)

你推进了@m。但不是月份名称:

declare @M int = 0
declare @SQL varchar(max) = ''
declare @Cnt int = 1
declare @Month varchar(25) 

while @Cnt <= 12
begin
    set @M = @M + 1
    set @Month = datename(m, '2016-' + convert(varchar(2), @M) + '-01')
    set @SQL = @SQL + 'select ' + convert(varchar(25), @M) + ' as M, ''' + @Month + ''' as Month'
    if  @Cnt <> 12 set @SQL = @SQL + ' Union All '  
    set @Cnt = @Cnt + 1



end

 exec  (@SQL)

答案 2 :(得分:0)

你没有在WHILE中使用@Month,这是你要找的代码:

import mechanize

br = mechanize.Browser()
br.set_handle_refresh(False)

url = 'http://www.example.com'
r = br.open(url, timeout = 2.0)

request = br.request
print(request.header_items())

--output:--
[('Host', 'www.example.com'), ('User-agent', 'Python-urllib/2.7')]