使用动态SQL时'CAST'错误附近的语法不正确

时间:2018-11-29 16:38:52

标签: tsql

declare @sql nvarchar(max)

declare @region as nvarchar(30)

set @region = 'Region'

set @sql = N'SELECT Year, @geo, 
[Segment],Age,

SUM(CAST([Units_Sold] as Float)) Total_Units,

Sum(case when [Make] ='+ 'Toyota'+ 'then CAST([Units_Sold] as float) else 0 end) 

Toyota_Total_Units, 

(case when SUM(CAST([Units_Sold] as float)) = 0 then' +'0'+

'else ((Sum(case when [Make] ='+ 'Toyota' + 

'then CAST([Units_Sold] as float) else 0 end)/SUM(CAST([Units_Sold] as 

float)))*100)

end) Market_Share

INTO #TYT_METRIC_CURRENT_GROUP FROM Toyota1 where Year =' + '2017'

+ 'Group BY

GROUPING SETS
 (
(Year,@geo,[Segment],Age),
(Year,@geo,[Segment]),
(Year,@geo) 
)  

 set @sql = replace(@sql, '@geo', @region)

 exec sp_executesql @sql

错误

“ CAST”附近的语法不正确。

1 个答案:

答案 0 :(得分:0)

declare @sql nvarchar(max)

declare @region as nvarchar(30)

set @region = 'Region'

set @sql = N'SELECT Year, @geo, [Segment],Age, SUM(CAST([Units_Sold] as Float)) Total_Units,
Sum(case when [Make] = ''Toyota'' then CAST([Units_Sold] as float) else 0 end)
Toyota_Total_Units, (case when SUM(CAST([Units_Sold] as float)) = 0 then 0 
else ((Sum(case when [Make] = ''Toyota'' then CAST([Units_Sold] as float) else 0 end)/SUM(CAST([Units_Sold] as
float)))*100)
end) Market_Share 
INTO #TYT_METRIC_CURRENT_GROUP FROM Toyota1 where Year = 2017
Group BY 
GROUPING SETS ( (Year,@geo,[Segment],Age), (Year,@geo,[Segment]), (Year,@geo) )'

set @sql = replace(@sql, '@geo', @region)

exec sp_executesql @sql