判断表中的数据是否被其他表中使用过!!

类别:数据库 点击:0 评论:0 推荐:


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
/*******************************************************************************/

本文地址:http://com.8s8s.com/it/it20750.htm