我正在尝试使用当前时段更新一年中的几个月。因此,我使用带有月份变量的switch语句。但是,我收到错误:
必须声明标量变量
我尝试了以下内容:
OAuthServiceConfig
和
DECLARE @DATE_AP dateTime
DECLARE @month varchar(max)
SET @DATE_AP= DATEADD(year, 0, GETDATE())
SET @month_AP = DATENAME(Month, @DATE_AP)
SELECT CAST(@month as VARchar(10))
select @periodsetvar = 'select CASE @month
when ''October'' then
''Update tbltimes set Periodyr = 01''
when ''November'' then
''Update tbltimes set Periodyr = 02''
when ''December'' then
''Update tbltimes set Periodyr = 03''
when ''January'' then
''Update tbltimes set Periodyr = 04''
when ''February'' then
''Update tbltimes set Periodyr = 05''
END'
exec (@periodsetvar)
答案 0 :(得分:4)
不使用易受SQL注入影响的动态SQL,而是使用如下的简单语句:
DECLARE @DATE_AP dateTime
Declare @periodsetvar char(2)
SET @DATE_AP= DATEADD(year, 0, GETDATE())
Set @periodsetvar = CASE DATENAME(Month, @DATE_AP)
when 'October' then '01'
when 'November' then '02'
when 'December' then '03'
when 'Janurary' then '04'
when 'February' then '05'
end
Update tbltimes
set Periodyr = @periodsetvar
如果你100%决定使用动态SQL,那么你应该确保你做得更安全和参数化,如下所示:
DECLARE @DATE_AP dateTime
DECLARE @month varchar(10)
SET @DATE_AP= DATEADD(year, 0, GETDATE())
SET @month = DATENAME(Month, @DATE_AP)
select @periodsetvar = 'select CASE @month
when ''October'' then
''Update tbltimes set Periodyr = 01''
when ''November'' then
''Update tbltimes set Periodyr = 02''
when ''December'' then
''Update tbltimes set Periodyr = 03''
when ''January'' then
''Update tbltimes set Periodyr = 04''
when ''February'' then
''Update tbltimes set Periodyr = 05''
END'
exec sp_executesql @periodsetvar, N'@month varchar(10)', @month
sp_executesql允许您在动态sql中声明参数,使其更安全。
答案 1 :(得分:0)
您需要为所有变量添加声明:
DECLARE @DATE_AP dateTime
DECLARE @month varchar(max)
DECLARE @month_AP varchar(max)
DECLARE @periodsetvar varchar(max)
SET @DATE_AP= DATEADD(year, 0, GETDATE())
SET @month_AP = DATENAME(Month, @DATE_AP)
SELECT CAST(@month as VARchar(10))
select @periodsetvar = 'select CASE'+ ' '+ @month+'
when ''October'' then
''Update tbltimes set Periodyr = 01''
when ''November'' then
''Update tbltimes set Periodyr = 02''
when ''December'' then
''Update tbltimes set Periodyr = 03''
when ''January'' then
''Update tbltimes set Periodyr = 04''
when ''February'' then
''Update tbltimes set Periodyr = 05''
END'
exec (@periodsetvar)
答案 2 :(得分:0)
如果您基本上想要使用动态SQL,则需要在动态查询中声明@month
变量:
DECLARE
@DATE_AP dateTime,
@month_AP varchar(max),
@periodsetvar varchar(max)
SET @DATE_AP= DATEADD(year, 0, GETDATE())
SET @month_AP= DATENAME(Month, @DATE_AP)
SELECT @periodsetvar =
'declare @month varchar(max)
set @month = ''' + @month_AP+ '''
select
CASE @month
when ''October'' then ''Update tbltimes set Periodyr = 01''
when ''November'' then ''Update tbltimes set Periodyr = 02''
when ''December'' then ''Update tbltimes set Periodyr = 03''
when ''January'' then ''Update tbltimes set Periodyr = 04''
when ''February'' then ''Update tbltimes set Periodyr = 05''
END'
exec (@periodsetvar)