sqlserver通过语句 根据表生成建表语句
时间: 2023-09-12 07:03:28 浏览: 88
SQL 数据库生成创建表语句
可以通过以下语句生成指定表的建表语句:
```
SELECT
'CREATE TABLE ' + TABLE_NAME + ' (' +
STUFF((
SELECT ', ' + COLUMN_NAME +
CASE
WHEN DATA_TYPE IN ('varchar', 'nvarchar', 'char', 'nchar') THEN '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR(4)) + ')'
WHEN DATA_TYPE IN ('decimal', 'numeric') THEN '(' + CAST(NUMERIC_PRECISION AS VARCHAR(4)) + ', ' + CAST(NUMERIC_SCALE AS VARCHAR(4)) + ')'
ELSE ''
END +
CASE WHEN IS_NULLABLE = 'YES' THEN ' NULL' ELSE ' NOT NULL' END
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = t.TABLE_NAME
ORDER BY ORDINAL_POSITION
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
+ ');'
FROM INFORMATION_SCHEMA.TABLES t
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'YourTableName'
```
将 `YourTableName` 替换为你所需生成建表语句的表名即可。执行该语句后,会生成该表的建表语句。
阅读全文