我正在编写sp以在asp.net页面中使用,该页面显示gridview(具有多个页面)和select查询的复选框。但是它在EXEC(@sql)
上给出了语法错误,在使用WITH...AS
后我是否可以在if中调用它?
SET @sql=@sql +' ' +' FROM DATASET WHERE (RowId BETWEEN (@page - 1) * @pageSize AND (@page) * @pageSize)
OR (@page IS NULL)'
if @filter='pt'
BEGIN
WITH DataSet AS
(
SELECT TOP 100 PERCENT
row_number() over(order by date desc) as 'RowId'
, convert(varchar(10), date 105) AS 'date'
, product1
, product2
, product3
, product4
, Y
, N
FROM (select date
, count(case when product='product1' then 1 else null end) as 'product1'
, count(case when product='product2' then 1 else null end) as 'product1'
, count(case when product='product3' then 1 else null end) as 'product1'
, count(case when onsale='Y' then 1 else null end) as 'Y'
, count(case when onsale='N' then 1 else null end) as 'N'
from dbo.vwSales
group by date) as o
WHERE
(date BETWEEN @from AND @to)
)
EXEC (@sql)
END
答案 0 :(得分:0)
你必须在Exec命令的变量中包含整个SQL,从"开始......"。
答案 1 :(得分:0)
除非我们在这里没有看到,否则没有理由在这里执行动态SQL。编写动态SQL并使用EXEC执行它通常是一种反模式,因为它使您可以编写一些带有安全问题的低效代码。
你能跑......
WITH DataSet AS
(
SELECT TOP 100 PERCENT
row_number() over(order by date desc) as 'RowId'
, convert(varchar(10), date 105) AS 'date'
, product1
, product2
, product3
, product4
, Y
, N
FROM (select date
, count(case when product='product1' then 1 else null end) as 'product1'
, count(case when product='product2' then 1 else null end) as 'product1'
, count(case when product='product3' then 1 else null end) as 'product1'
, count(case when onsale='Y' then 1 else null end) as 'Y'
, count(case when onsale='N' then 1 else null end) as 'N'
from dbo.vwSales
group by date) as o
WHERE
(date BETWEEN @from AND @to)
)
FROM DATASET WHERE (RowId BETWEEN (@page - 1) * @pageSize AND (@page) * @pageSize)
OR (@page IS NULL)
另请注意,“TOP 100%”是不必要的。