可否将一个动态SQL查询建为一个视图
查询如下(具体查询语句不是重点):
DECLARE @sql varchar(8000)
set @sql = 'SELECT [CusID] '
select @sql = @sql + ', MAX(CASE [GoodSort] WHEN ''' + GoodsSort + ''' THEN SUMRRCus else 0 end) [' + GoodsSort + ']'
FROM (select distinct GoodsSort from GoodsSort) AS G
set @sql = @sql + ' FROM
(SELECT [CusID],[GoodSort],SUM(SUMRR) SUMRRCus FROM
(SELECT [CusID],A.[SaleID],[GoodSort], SUMRR FROM [SaleInfo] A,
(SELECT [SaleID],[GoodSort], SUM([RealReceive]) SUMRR FROM
[SaleDetail] GROUP BY [SaleID], [GoodSort]
) B
WHERE A.[SaleID]=B.[SaleID]
) C GROUP BY [CusID],[GoodSort]
) D
GROUP BY [CusID]'
exec(@sql)
可以查出目标数据,
重点是如何将结果集建为一个视图?
附:
尝试了正常创建视图的方式:
CREATE VIEW [vw_SumRRByCus] AS
DECLARE @sql varchar(8000)
……
exec(@sql)
报错:
服务器: 消息 156,级别 15,状态 1,过程 vw_SumRRByCus,行 2
在关键字 'DECLARE' 附近有语法错误。
[解决办法]
答案是不能的。
A view can contain only a single SQL statement (if more than one should include UNION/EXCEPT/INTERSECTION/etc), it cannot contain variable declarations, assignments, control flow, loops, or any kind of business logic, etc.
[解决办法]
你为什么不用存储过程呢?
[解决办法]
没有动态视图,视图里面只能有select语句,不能有declare之类的语句
[解决办法]
declare @tb table(id int,name varchar(50))
declare @str varchar(1000)='';
set @str='select top 10 number as id,name from master.[dbo].[spt_values]'
insert @tb
Exec (@str)
select * from @tb