开发者

adding a constraint that checks existence of stored proc

开发者 https://www.devze.com 2023-01-26 04:42 出处:网络
I am using SQL Server 2005 and in one of the tables i have a column that stores stored proc name. While inserting values in that开发者_开发知识库 column I want to ensure that a stored proc of that nam

I am using SQL Server 2005 and in one of the tables i have a column that stores stored proc name. While inserting values in that开发者_开发知识库 column I want to ensure that a stored proc of that name exists in the database.

ALTER TABLE MyTable WITH CHECK 
   ADD CONSTRAINT [CK_MyTable_MyColumn] CHECK ((SELECT COUNT(*)  FROM sys.sysobjects WHERE id = object_id(MyColumn) AND OBJECTPROPERTY(id, N'IsProcedure')=1) = 1)

but this gives the following error

Subqueries are not allowed in this context. Only scalar expressions are allowed.

How can I do this.


Functions are allowed:

create function dbo.IsProcedure(@ProcName sysname) returns bit as
return (SELECT COUNT(*) FROM sys.sysobjects 
  where id = object_id(MyColumn) and OBJECTPROPERTY(id, N'IsProcedure')=1);
go

ALTER TABLE MyTable WITH CHECK ADD CONSTRAINT [CK_MyTable_MyColumn]
CHECK (dbo.IsProcedure(MyColumn) = 1);


Note that this type of constraint is only guaranteed to be true at the time a record is inserted or updated. The proc can be dropped without consequence. You may need to add a DDL trigger to catch things which get dropped which have references in the table and/or an exception reporting procedure which runs on a regular basis to monitor your system's health to ensure any procedure in the table actually exists.

0

精彩评论

暂无评论...
验证码 换一张
取 消