我的表中有一个名为MealType
( VARCHAR
)的列,其CHECK
约束为{"Veg", "NonVeg", "Vegan"}
这将负责插入。
我想显示这些选项以供选择,但我无法找出 SQL 查询来找出表中特定列的约束。
乍一看 MS SQL 服务器中的系统表,我似乎需要使用 MS SQL 的 API 来获取信息。我希望 SQL 查询本身能够得到它。
我的表中有一个名为MealType
( VARCHAR
)的列,其CHECK
约束为{"Veg", "NonVeg", "Vegan"}
这将负责插入。
我想显示这些选项以供选择,但我无法找出 SQL 查询来找出表中特定列的约束。
乍一看 MS SQL 服务器中的系统表,我似乎需要使用 MS SQL 的 API 来获取信息。我希望 SQL 查询本身能够得到它。
最简单快捷的方法是使用:
sp_help 'TableName'
此查询应向您显示表上的所有约束:
select chk.definition
from sys.check_constraints chk
inner join sys.columns col
on chk.parent_object_id = col.object_id
inner join sys.tables st
on chk.parent_object_id = st.object_id
where
st.name = 'Tablename'
and col.column_id = chk.parent_column_id
可以用这个替换select语句:
select substring(chk.Definition,2,3),substring(chk.Definition,9,6),substring(chk.Definition,20,5)
SELECT obj_table.NAME AS 'table',
columns.NAME AS 'column',
obj_Constraint.NAME AS 'constraint',
obj_Constraint.type AS 'type'
FROM sys.objects obj_table
JOIN sys.objects obj_Constraint
ON obj_table.object_id = obj_Constraint.parent_object_id
JOIN sys.sysconstraints constraints
ON constraints.constid = obj_Constraint.object_id
JOIN sys.columns columns
ON columns.object_id = obj_table.object_id
AND columns.column_id = constraints.colid
WHERE obj_table.NAME='table_name'
ORDER BY 'table'
您可以使用
sp_helpconstraint 'tableName', 'nomsg'
获取表的所有约束。
“sp_help”返回更多信息。
感谢orgtrigger的示例!我对其进行了改进,以便能够删除不必要的约束(然后在需要时创建它们的修改版本)。也许这段代码对任何人都有用。
-- removing old constraints
DECLARE @ConstraintNames TABLE (Name VARCHAR(MAX), RowNum INT)
DECLARE @TableName VARCHAR(100) = 'HubSpot'
INSERT @ConstraintNames
SELECT [constraint].name,
ROW_NUMBER() OVER (ORDER BY [constraint].[name]) AS RowNum
FROM sys.default_constraints [constraint]
INNER JOIN sys.columns col
ON [constraint].parent_object_id = col.object_id
INNER JOIN sys.tables st
ON [constraint].parent_object_id = st.object_id
WHERE
st.name = @TableName
AND col.name IN ('ForceUpdateOnImport', 'ForceUpdateOnExport')
AND col.column_id = [constraint].parent_column_id
SELECT * FROM @ConstraintNames
DECLARE @i INT = 1,
@count INT,
@constraintName VARCHAR(MAX),
@sql VARCHAR(MAX)
SELECT @count = COUNT(1) FROM @ConstraintNames
WHILE @i <= @count
BEGIN
SELECT @constraintName = cn.Name FROM @ConstraintNames cn WHERE cn.RowNum = @i
SET @sql = 'ALTER TABLE ' + @TableName + ' DROP CONSTRAINT ' + @constraintName
EXEC (@sql)
SET @i = @i + 1
END