在声明表格时我无法创建视图

时间:2015-02-15 05:09:39

标签: sql asp.net-mvc entity-framework

此代码显示我的软件中的提醒工具,但在我的程序中,我现在使用EF 我想创建视图并在C#

中使用它
CREATE VIEW s AS
(
DECLARE @ta AS TABLE(NAME NVARCHAR(30),qty INT,so INT,tar INT) 
INSERT INTO @ta 
SELECT p.Name,t.Qty,t.Source,t.target FROM dbo.Products p
JOIN dbo.TradeOff t ON t.ProductId = p.ProductID 
DECLARE @source AS TABLE(NAME NVARCHAR(30),qty INT,so INT) 
DECLARE @tar AS TABLE(NAME NVARCHAR(30),qty INT,tar INT) 

INSERT INTO @source 
SELECT t1.NAME,SUM(t1.qty),t1.so  FROM @ta t1
GROUP BY t1.so,t1.NAME

INSERT INTO @tar 
SELECT t1.NAME,SUM(t1.qty),t1.tar  FROM @ta t1

GROUP BY t1.tar,t1.NAME

SELECT s.NAME,ISNULL(t.Qty,0 )-ISNULL(s.qty,0),ISNULL(t.tar,s.so) FROM @tar t 
RIGHT JOIN @source s ON s.so=t.tar AND s.NAME=t.NAME 
)

2 个答案:

答案 0 :(得分:0)

您无法在table variable内使用view。试试这个

CREATE VIEW s
AS
  SELECT s.NAME,
         Isnull(t.Qty, 0) - Isnull(s.qty, 0),
         Isnull(t.tar, s.so)
  FROM   (SELECT t1.NAME,
                 Sum(t1.qty),
                 t1.tar
          FROM   (SELECT p.NAME,
                         t.Qty,
                         t.Source,
                         t.target
                  FROM   dbo.Products p
                         JOIN dbo.TradeOff t
                           ON t.ProductId = p.ProductID) t1
          GROUP  BY t1.tar,
                    t1.NAME) t
         RIGHT JOIN (SELECT t1.NAME,
                            Sum(t1.qty),
                            t1.so
                     FROM   (SELECT p.NAME,
                                    t.Qty,
                                    t.Source,
                                    t.target
                             FROM   dbo.Products p
                                    JOIN dbo.TradeOff t
                                      ON t.ProductId = p.ProductID) t1
                     GROUP  BY t1.so,
                               t1.NAME) s
                 ON s.so = t.tar
                    AND s.NAME = t.NAME 

答案 1 :(得分:0)

如果您需要使用表变量,您可以使用存储过程来表示值函数来实现这一点但是这些比视图慢,并且根据您要使用数据的位置将确定哪种解决方案最符合您的要求