选择varchar值作为动态sql查询中的列名称
在我的项目中,我使用SQL Server 2008作为后端。我在使用动态sql的过程中遇到了一个问题。查看我正在使用的动态sql的示例代码。选择varchar值作为动态sql查询中的列名称
Declare @Sql varchar(Max)
set @Sql='Declare @Counter1 int=1; Declare @Counter2 int;
Declare @PrevMonthAmt decimal(18,2);
Declare @CurrMonthAmt decimal(18,2);
Declare @MonthName varchar(100);
while @Counter1<=(select count(*) from #Tab1)
begin
set @Counter2 = (select count(*) from #TabMonths)
set @MonthName = (select [Month] from #TabMonths where [email protected])
while @Counter2>=1
begin
select @[email protected] from #Tab1 where [email protected]
select @[email protected] from #Tab1 where Id=(@Counter1-1)
update #Tab1 set @MonthName=(@[email protected]) where [email protected]
set @[email protected]
end
set @Counter1= @Counter1+1
end;
select *from #Tab1
' Exec @Sql
此处临时表#Tab1包含员工月薪明细,#TabMonths包含所有月份的列表。这两个#Table1 & #TabMonths的月份列都不是静态字段。它将自动从前端UI中的用户下拉选择(开始年和结束年)生成。如果用户选择是启动年:2013 &末年:2014年,将在这两个#TAB1 &像扬,2013年2月,2013最多至12月#TabMonth创建24个月动态栏目,2014年
我想在#Tab1中更新当前月薪和上月薪水之间的差异。但@MonthName不考虑列名,但始终将@MonthName视为varchar,同时从@ Tab1中选择。所以我没有得到一个员工在特定月份的工资。我必须在动态查询中希望这可能。任何帮助,将不胜感激。
你的问题在于这三行代码。第一行和第二行试图将一个varchar分配给一个十进制变量。第三行尝试将一个十进制值分配给varchar变量。
select @[email protected] from #Tab1 where [email protected]
select @[email protected] from #Tab1 where Id=(@Counter1-1)
update #Tab1 set @MonthName=(@[email protected]) where [email protected]
作为一个心理练习,让我们用这里的值替换变量。假设#Tab1包含如下所示的数据,其中...表示4-10月,4月至10月。
Id MonthName
---------------
1 January
2 February
3 March
... ...
11 November
12 December
关注这行代码:
select @[email protected] from #Tab1 where [email protected]
替代2 @Counter1
,和 “日” 为@MonthName
,所以代码现在看起来像这样:
select @CurrMonthAmt="February" from #Tab1 where Id=2
你是试图将@CurrMonthAmt
(代表某人的工资的小数)分配给varchar值"February"
而不是十进制值,如5000.00
。就个人而言,我宁愿支付5000.00
而不是"February"
。
我知道这个问题,并在我的文章中指定。这里我想要的代码是从#Tab1中选择@ CurrMonthAmt = [February,2013],其中Id = 2。这里[2013年2月]是在#Tab1和#TabMonths中生成的动态列。因此,我将为2013年2月份的员工收取工资。 – Jayaraj 2014-11-08 20:42:09
对不起,我误解了你的表格结构。我会审查和修改我的答案。 – mhester 2014-11-08 21:27:27
也许这会帮助你。http://stackoverflow.com/questions/11869820/tsql-passing-a-varchar-variable-of-column-name-to-sum-function – mhester 2014-11-08 22:36:08
'Declare @ Counter1 int = 1;'不应该是两行吗?一个是'DECLARE',另一个是'SET'? – programmer43229 2014-11-08 19:37:13
是的,这是两行。 – Jayaraj 2014-11-08 19:42:50
一瞥代码表明你不需要为你想要的结果做一个嵌套循环。我可能会建议你再问一个问题,看看是否有更好的方法来获取你想要的信息。你甚至可以设置一个SQL小提琴。 – 2014-11-08 20:04:43