使用用户定义函数作为临时表中的约束

时间:2014-08-02 22:04:34

标签: sql-server tsql constraints user-defined-functions temp-tables

我正在尝试创建一个在约束中使用UDF的临时表。我收到以下错误消息:

  

Msg 4121,Level 16,State 1,Line 1
  找不到列dbo或用户定义的函数或聚合dbo.CK_LoseTeamSportExists,或者名称不明确。

我已经测试了这个功能,它可以在其他环境中使用。任何的想法?

以下所有代码:

CREATE FUNCTION dbo.CK_LoseTeamSportExists
(
    @loseteam     INT,
    @sportid      INT
)
RETURNS BIT
AS
BEGIN
    DECLARE @return BIT  
    IF EXISTS 
       (
           SELECT    TeamID,
                 sportid
           FROM  Link_TeamSport
           WHERE     (TeamID = @loseteam AND SportID = @sportid)
       )
        SET @return = 1
    ELSE
        SET @return = 0

    RETURN @return
END
GO

CREATE TABLE #check
(
    SportID        INT,
    WinTeamID      INT,
    LoseTeamID     INT,
    CHECK          ((dbo.CK_LoseTeamSportExists(LoseTeamID, SportID) = 1))
)

1 个答案:

答案 0 :(得分:0)

这应该有用。

USE [tempdb]
GO
CREATE FUNCTION dbo.CK_LoseTeamSportExists
(
    @loseteam     INT,
    @sportid      INT
)
RETURNS BIT
AS
BEGIN
    DECLARE @return BIT  
    IF EXISTS 
       (
           SELECT    TeamID,
                 sportid
           FROM  Link_TeamSport
           WHERE     (TeamID = @loseteam AND SportID = @sportid)
       )
        SET @return = 1
    ELSE
        SET @return = 0

    RETURN @return
END
GO

IF OBJECT_ID(N'tempdb..#check')>0
DROP TABLE #check
GO

CREATE TABLE #check
(
    SportID        INT,
    WinTeamID      INT,
    LoseTeamID     INT,
    CHECK          ((dbo.CK_LoseTeamSportExists(LoseTeamID, SportID) = 1))
)