|
|
|
User-defined functions in SQL2000 provide a powerful way to reuse code / logic. This example shows how you can use UDFs in CHECK & DEFAULT constraints of a table. |
Click here to copy the following block | USE tempdb; GO
CREATE SCHEMA AUTHORIZATION dbo CREATE TABLE PkTbl ( Col1 int IDENTITY PRIMARY KEY ) CREATE TABLE FkTbl ( Col1 int FOREIGN KEY REFERENCES PkTbl( Col1 ) , Col2 int ) GO
CREATE FUNCTION ChkPrimaryVal ( @Val int ) RETURNS INTEGER WITH SCHEMABINDING AS BEGIN RETURN( SELECT COUNT( * ) FROM dbo.FkTbl WHERE Col1 = @Val ) END GO CREATE FUNCTION RandDefault ( ) RETURNS INTEGER WITH SCHEMABINDING AS BEGIN RETURN( @@OPTIONS % @@SPID ) END GO
ALTER TABLE FkTbl ADD CONSTRAINT CK_FkTbl_ChkPrimaryVal CHECK ( dbo.ChkPrimaryVal( Col1 ) = 1 ) , CONSTRAINT DF_FkTbl_RandDefault DEFAULT ( dbo.RandDefault() ) FOR Col2 GO
INSERT INTO PkTbl DEFAULT VALUES; PRINT 'Adding a new row into FkTbl...'; INSERT INTO FkTbl VALUES ( 1 , DEFAULT ); GO
PRINT '' PRINT 'Adding a new row into FkTbl with non-existant value...'; INSERT INTO FkTbl VALUES ( 11 , DEFAULT );
GO
PRINT '' PRINT 'Adding a duplicate value into FkTbl...'; INSERT INTO FkTbl VALUES ( 1 , DEFAULT );
GO
SELECT * FROM FkTbl;
GO
ALTER TABLE FkTbl DROP CONSTRAINT CK_FkTbl_ChkPrimaryVal , DF_FkTbl_RandDefault; DROP FUNCTION dbo.ChkPrimaryVal; DROP FUNCTION dbo.RandDefault; DROP TABLE FkTbl; DROP TABLE PkTbl; GO |
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|