我试图首先检查函数是否存在然后创建它,如果它不存在。
我从函数中收到此错误:
IF NOT EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[GetRelativeExpiry]') AND type in (N'U'))
BEGIN
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [dbo].[GetRelativeExpiry]
(
@Date DATE,
@N INT
)
RETURNS DATE
AS
BEGIN
-- Declare the return variable here
DECLARE @Expiry as DATE;
IF @N > 0
BEGIN
SELECT @Expiry = MAX(E2.Expiry)
FROM (SELECT TOP(@N) Expiry
FROM ExpiryDates E1
WHERE E1.Expiry >= @date
ORDER BY E1.Expiry) AS E2
END
ELSE
BEGIN
SELECT @Expiry = MIN(E2.Expiry)
FROM (SELECT TOP(-@N) Expiry
FROM ExpiryDates E1
WHERE E1.Expiry <= @date
ORDER BY E1.Expiry DESC) AS E2
END
RETURN @Expiry
END
END
我不确定为什么会收到此错误,有人可以帮忙吗? 我正在使用Microsoft SQL Server Management Studio 2014
答案 0 :(得分:3)
CREATE
语句,无论是TYPE, PROCEDURE, FUNCTION, ...
,都应该是批处理中的第一个语句。
要像你这样批量解决这个问题,请使用CREATE
执行sp_executesql
语句,如下所示:
EXEC sp_executesql N'
-- your CREATE statement here
';
答案 1 :(得分:1)