我有一个相当复杂的CTE,我试图将其合并到存储过程中。它只适用于直接从SQL Server Management Studio运行。当我尝试创建存储过程时,出现错误:
Msg 102,Level 15,State 1,Procedure spMyCrazyProc,Line 56
附近的语法不正确
','。
在尝试将CTE合并到存储过程中时,我在语法上做错了什么?
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spMyCrazyProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spMyCrazyProc]
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE dbo.spMyCrazyProc
@CompanyId Int,
@EmployeeIds varchar(MAX)
AS
;with SelectedEmployees as (
select * from vwEmployee e
where e.CompanyId = @CompanyId
and (@EmployeeIds is null or @EmployeeIds='' or exists(select ce.SelectedEmployeeId from #myTmpTable ce where ce.SelectedEmployeeId=e.EmployeeId)
), MyStuffA as (
select * from SelectedEmployees
)
select * from MyStuffA
GO
答案 0 :(得分:4)
使用合理的编码约定并考虑可读性(缩进,回车)会更清楚地产生这个简单的错误。删除了500个字符宽行的代码:
;with SelectedEmployees as
(
select * from vwEmployee e
where e.CompanyId = @CompanyId
and
(
@EmployeeIds is null or @EmployeeIds='' or exists
(
select ce.SelectedEmployeeId from #myTmpTable ce
where ce.SelectedEmployeeId=e.EmployeeId
)
----^----- oops! Missing closing paren here.
), MyStuffA as
(
select * from SelectedEmployees
)
select * from MyStuffA