用SQL server的语法来写,请设计一个存储过程,要求输入表名,输出这张表的建表语句和创建约束的语句
时间: 2024-05-29 11:12:46 浏览: 110
CREATE PROCEDURE sp_GetTableSchema
@TableName VARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Schema NVARCHAR(MAX);
DECLARE @Constraints NVARCHAR(MAX);
--获取表的列信息
SELECT @Schema = COALESCE(@Schema + ', ', '') + COLUMN_NAME + ' ' + DATA_TYPE +
CASE WHEN CHARACTER_MAXIMUM_LENGTH IS NOT NULL THEN '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS NVARCHAR(10)) + ')' ELSE '' END +
CASE WHEN IS_NULLABLE = 'NO' THEN ' NOT NULL' ELSE '' END
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
ORDER BY ORDINAL_POSITION;
--获取表的约束信息
SELECT @Constraints = COALESCE(@Constraints + CHAR(13) + CHAR(10), '') + CONSTRAINT_NAME + ' ' +
CASE WHEN CONSTRAINT_TYPE = 'PRIMARY KEY' THEN 'PRIMARY KEY (' +
(SELECT COALESCE(COLUMN_NAME + ', ', '') FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = @TableName AND CONSTRAINT_NAME = C.CONSTRAINT_NAME AND ORDINAL_POSITION IS NOT NULL
ORDER BY ORDINAL_POSITION FOR XML PATH('')) + ')'
WHEN CONSTRAINT_TYPE = 'FOREIGN KEY' THEN 'FOREIGN KEY (' +
(SELECT COALESCE(COLUMN_NAME + ', ', '') FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = @TableName AND CONSTRAINT_NAME = C.CONSTRAINT_NAME AND ORDINAL_POSITION IS NOT NULL
ORDER BY ORDINAL_POSITION FOR XML PATH('')) + ') REFERENCES ' +
(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME = C.CONSTRAINT_NAME)
ELSE '' END
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
WHERE TABLE_NAME = @TableName;
--输出建表语句和创建约束语句
SELECT 'CREATE TABLE ' + @TableName + ' (' + @Schema + ');' + CHAR(13) + CHAR(10) + @Constraints;
END
GO
--测试存储过程
EXEC sp_GetTableSchema 'Employees'; --替换为实际表名
阅读全文