Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL Server:创建带条件的外键_Sql_Sql Server_Sql Server 2012_Ssms - Fatal编程技术网

SQL Server:创建带条件的外键

SQL Server:创建带条件的外键,sql,sql-server,sql-server-2012,ssms,Sql,Sql Server,Sql Server 2012,Ssms,我正在为一家公司设计一个新的数据库,试图用外键等保持严格的约束以保证完整性。我有一个表[Member],其中包含系统中的公司。此表有一列[internalContact],用于我们公司中与此成员打交道的用户,该成员通过用户id将外部链接到用户表 我想知道的是,由于users表包含内部和外部用户,是否可以为外键分配一个条件。即,该字段仅接受用户类型为5的用户id。这是可以做到的,还是只能在应用程序代码中控制 谢谢您可以为此使用检查约束。 (代码未经测试,其中将包含一些语法错误) 然后只需创建一个函

我正在为一家公司设计一个新的数据库,试图用外键等保持严格的约束以保证完整性。我有一个表
[Member]
,其中包含系统中的公司。此表有一列
[internalContact]
,用于我们公司中与此成员打交道的用户,该成员通过用户id将外部链接到用户表

我想知道的是,由于users表包含内部和外部用户,是否可以为外键分配一个条件。即,该字段仅接受用户类型为5的用户id。这是可以做到的,还是只能在应用程序代码中控制


谢谢

您可以为此使用检查约束。 (代码未经测试,其中将包含一些语法错误)

然后只需创建一个函数
isInternalUser
,如果用户处于ok状态,则返回1作为内部联系人

CREATE FUNCTION isInternalUser ( @userId int(10) )
  RETURNS int
  AS
  BEGIN
      DECLARE @tmp int
        SELECT @tmp = count(*)
          FROM users
        WHERE userId = @UserId and <check to see if user is internal>
      RETURN(@CtrPrice)
  END
GO 
创建函数isInternalUser(@userId int(10))
返回整数
作为
开始
声明@tmp int
选择@tmp=count(*)
来自用户
其中userId=@userId和
退货(@CtrPrice)
结束
去

此问题的可能重复:我认为您可以创建检查约束。这也是替代触发器的理想场景。IMHO,替代触发器将更优化。我错了吗?您也可以使用触发器执行此检查:
CREATE FUNCTION isInternalUser ( @userId int(10) )
  RETURNS int
  AS
  BEGIN
      DECLARE @tmp int
        SELECT @tmp = count(*)
          FROM users
        WHERE userId = @UserId and <check to see if user is internal>
      RETURN(@CtrPrice)
  END
GO