SQL,'创建视图'必须是查询批处理中的第一个语句

时间:2018-03-05 12:06:31

标签: sql sql-server-2008 variables declare create-view

我得到以下错误:

  

'创建视图'必须是查询批处理中的第一个语句。

我尝试创建视图并在查询中插入日期参数​​作为变量。 出于某种原因,它不起作用,任何想法如何克服它? 这是查询

 DECLARE **@StartDate** date='2017-05-29 00:00:00';

GO 
 DECLARE **@EndDate** date='2018-03-04 00:00:00';

GO

 CREATE  VIEW [FG_Cargo] AS

 SELECT c.ContainerName,P.Description,
 WFS.WorkflowStepName,WFB.WorkflowName,  HML.TxnDate, hml.CDOTypeId,
 hml.TxnType

 FROM Container C join HistoryCrossRef HCR on
 (c.ContainerId=HCR.TrackingId) JOIN HistoryMainline HML
 ON(HCR.HistoryId=HML.HistoryId) JOIN Product P ON
 (C.ProductId=P.ProductId) JOIN WorkflowStep WFS ON
 (HML.WorkflowStepId=WFS.WorkflowStepId) JOIN Workflow WF ON
 (WFS.WorkflowId=WF.WorkflowId) JOIN WorkflowBase WFB ON
 (WF.WorkflowBaseId=wfb.WorkflowBaseId)

 WHERE C.ContainerName LIKE('KT%') AND WFS.WorkflowStepName='release
 for shipping' AND  TxnType='6640' AND HML.TxnDate BETWEEN
 **@StartDate** AND **@EndDate** ;

 GO

 SELECT* FROM FG_Cargo

2 个答案:

答案 0 :(得分:1)

您无法在视图中放置变量。相反,使用内联表函数:

CREATE FUNCTION dbo.ufn_fg_cargo (
    @StartDate date,
    @EndDate date
) RETURNS table
AS
RETURN (SELECT c.ContainerName, P.Description, WFS.WorkflowStepName, 
               WFB.WorkflowName, HML.TxnDate, hml.CDOTypeId, hml.TxnType
        FROM Container C JOIN
             HistoryCrossRef HCR 
             ON c.ContainerId = HCR.TrackingId JOIN
             HistoryMainline HML
             ON HCR.HistoryId = HML.HistoryId JOIN
             Product P
             ON C.ProductId = P.ProductId JOIN
             WorkflowStep WFS
             ON HML.WorkflowStepId = WFS.WorkflowStepId JOIN
             Workflow WF
             ON WFS.WorkflowId = WF.WorkflowId JOIN
             WorkflowBase WFB
             ON WF.WorkflowBaseId = wfb.WorkflowBaseId
        WHERE C.ContainerName LIKE 'KT%' AND 
              WFS.WorkflowStepName = 'release for shipping' AND 
              TxnType = '6640' AND
              HML.TxnDate BETWEEN @StartDate AND @EndDate 
       );

然后您可以将其用作:

select c.*
from dbo.ufn_fg_cargo('2017-05-29', '2018-03-04') c

答案 1 :(得分:0)

如前所述,您不能将变量放在视图中。你有两个选择。一种是创建一个返回表的函数(根据@GordonLinoff提供的答案)。另一个选项,这在很大程度上取决于视图所代表的数据量,是构建包含所有日期的视图,然后再进行过滤。

我必须确认这一点,但我猜测使用函数会在每次访问函数时强制重建表,而只有在基础表/数据发生变化时才构建/重新构建视图?

修改

要消除错误,并假设您想要一个视图,您可以执行以下操作:

IF NOT EXISTS (
    SELECT * FROM INFORMATION_SCHEMA.VIEWS  
    WHERE TABLE_SCHEMA = 'dbo' 
        AND TABLE_NAME = 'FG_Cargo'
)
BEGIN
    EXECUTE('
        CREATE VIEW [dbo].[FG_Cargo]
        AS
            SELECT 
        ...
    ')
END;
GO

这确保CREATE VIEW语句肯定是查询批处理中的第一个语句,并且可以避免错误。您只需要确保查询中的任何引号都已适当转义。