[摘要]CREATE PROCEDURE dbo.SystemFuntion_HasBeUsed @PTableName Varchar(100), --要检查数据是否被使用的主键表名称 @PKValue ...
CREATE PROCEDURE dbo.SystemFuntion_HasBeUsed
@PTableName Varchar(100), --要检查数据是否被使用的主键表名称
@PKValue INT, --主键字段的值
@IsUsed INT OUTPUT
AS
DECLARE @TableName VARCHAR(100) --外键表的名称
DECLARE @FKName VARCHAR(100) --外键字段名称
DECLARE @FKey INT
DECLARE @SQL VARCHAR(8000)
SET @sql = ’SELECT 0 as colCount into #tempTableCol UNION ’
DECLARE cursorFKTable CURSOR FOR
SELECT b.[name] AS TableName , a.fkey
FROM sysforeignkeys a INNER JOIN sysobjects b on a.fkeyid=b.[id] INNER JOIN sysobjects c on a.rkeyid=c.[id]
WHERE c.[name]=@PTableName
OPEN cursorFKTable
FETCH NEXT FROM cursorFKTable INTO @TableName,@FKey
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @FKName = a.[name] FROM syscolumns a INNER join sysobjects b ON a.[id]=b.[id] WHERE b.[name]=@TableName and @FKey=a.colid
SET @sql = @sql + ’SELECT CASE WHEN COUNT(*)=0 THEN 0 ELSE 1 END FROM ’ + @TableName +’ WHERE ’ + @FKName + ’=’ + CAST(@PKValue AS VARCHAR(100))
SET @sql = @sql + ’ UNION ’
FETCH NEXT FROM cursorFKTable INTO @TableName,@FKey
END
CLOSE cursorFKTable
DEALLOCATE cursorFKTable
SELECT @sql = left(@sql,len(@sql)-6)
exec(@sql)
SELECT @IsUsed = @@ROWCOUNT-1
GO
使用方法:
/***********获取当前主键值是否被其他表使用过(@HasPKValueBeUsed as HasPKValueBeUsed)*************/
DECLARE @HasPKValueBeUsed INT
EXECUTE SystemFuntion_HasBeUsed ’TLSubjectPlan’,@SubjectPlanID,@IsUsed=@HasPKValueBeUsed OUTPUT
/*******************************************************************************/
全新的路由器不仅让你更稳定快速地连接无线网络,更可以让家中的智能设备连接在一起。
……