SQL Server如何获取外键约束的代码

时间:2012-02-17 21:45:16

标签: sql-server sql-server-2005

我可以使用syscomments表获取存储过程的代码。

select so.name, sc.text as storedproccode
from sysobjects so (nolock)
inner join syscomments sc (nolock) on sc.id = so.id
where so.name = 'tablename'

如何获取特定外键约束的代码?我有外键名。

让我澄清一下我在寻找什么。

我在对象资源管理器中找到了我的表并展开了键列表。如果有主键,我可以右键单击主键约束并在新窗口中调出脚本。

代码如下所示:

USE [Gemini]
GO
/****** Object:  Index [PK_CM_FULFILLMENT_HISTORY]    Script Date: 02/17/2012 16:50:23 ******/
ALTER TABLE [dbo].[CM_FULFILLMENT_HISTORY] ADD  CONSTRAINT [PK_CM_FULFILLMENT_HISTORY] PRIMARY KEY NONCLUSTERED 
(
    [pan] ASC,
    [RequestCode] ASC,
    [RequestDate] ASC
)WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [GEMINI_12_Indx_FG]

我也可以使用外键约束来完成此操作。

有没有办法检索这些约束的代码(脚本)?

由于

3 个答案:

答案 0 :(得分:1)

  

如何获取特定外键约束的代码?

你不可能因为它不存在。配置Forein键约束,然后将管理信息保存在表中,但没有“代码”运行。

如果查看INFORMATION_SCHEMA,您会发现可以找出存在哪些约束以及它们引用的内容。但是没有“代码”。当您创建外键约束时,配置条目在描述约束的约束表中进行。 FK constriaint不是存储过程。

答案 1 :(得分:1)

查看sys.foreign_keyssys.foreign_key_columns。前者会告诉你列中的外键是什么,后者会告诉你哪些列在哪些外键中。

答案 2 :(得分:0)

我发现了一个可以解决问题的脚本。

Declare        @dbname varchar(128)
            ,  @tablename varchar(128)
            ,  @query nvarchar(4000)


select   @dbname = 'gemini'
       , @tablename = 'cm_fulfillment_house'


SET @QUERY = 
'USE ' + @DBNAME + '


SELECT CAST(F.NAME AS VARCHAR(255)) AS ForeignKeyName,
CAST(c.name as varchar(255)) AS ForeignTable,
CAST(fc.name as varchar(255)) AS ForeignColumn,
cast(fc2.name as varchar(255)) as ForeignColumn2,
CAST(p.name as varchar(255)) AS PrimaryTable,
CAST(rc.name as varchar(255)) AS PrimaryColumn,
cast(rc2.name as varchar(255)) as PrimaryColumn2
INTO #GetFKConstraints 
FROM SYSOBJECTS F 
INNER JOIN SYSOBJECTS C ON F.PARENT_OBJ = C.ID
INNER JOIN SYSREFERENCES R on F.ID = R.CONSTID 
INNER JOIN SYSOBJECTS P ON R.RKEYID = P.ID
INNER JOIN SYSCOLUMNS RC ON R.RKEYID = RC.ID AND R.RKEY1 = RC.COLID
INNER JOIN SYSCOLUMNS FC ON R.FKEYID = FC.ID AND R.FKEY1 = FC.COLID
left join syscolumns rc2 on r.rkeyid = rc2.id and r.rkey2 = rc.colid
left join syscolumns fc2 on r.fkeyid = fc2.id and r.fkey2 = fc.colid
WHERE F.TYPE = '+'''F'''+''

select @query = @query + ' and c.name = ''' + @tablename + ''''

+ '

--SELECT * from #GetFKConstraints'+'

SELECT ' + '''ALTER TABLE ''' + '+ ForeignTable + ' + ''' 
DROP CONSTRAINT ''' + '+ ForeignKeyName 
FROM #GetFKConstraints 
ORDER BY ForeignTable'
+'

SELECT ' + '''ALTER TABLE ''' + '+ ForeignTable +' + ''' 
ADD CONSTRAINT ''' + '+ ForeignKeyName +' 
+ ''' FOREIGN KEY ('''+ ' + ForeignColumn + '+ ''') 
REFERENCES ''' + '+ PrimaryTable + ' + '''(''' + '+ PrimaryColumn + '+ ''')''' +
'FROM #GetFKConstraints 
ORDER BY ForeignTable
'
select @query

EXEC (@QUERY)
GO