在SQL Server Management Studio中,有一个“生成和发布脚本向导”上下文菜单选项,可自动为表的数据生成插入语句脚本。
就我而言,我只能使用命令行访问数据库。含义我无法访问“生成和发布脚本向导”。
是否可以使用纯SQL或T-SQL命令行实现类似的功能?
答案 0 :(得分:0)
这是基于系统视图的基本SQL构建插件:
DECLARE @sqlinsert AS VARCHAR(MAX) = ''
DECLARE @tbl AS VARCHAR(128)='dbo.mytable'
SET @sqlinsert = 'DECLARE
'
SELECT @sqlinsert = @sqlinsert + '
@ins_' + c.name + ' ' + t.name
+ IIF(t.max_length>=8000,'('+ CONVERT(VARCHAR(16),c.max_length) +')','')+ ','--c.column_id, c.name,c.system_type_id,t.name,c.max_length,t.max_length,c.*
FROM sys.tables a
JOIN sys.schemas b ON a.schema_id = b.schema_id
JOIN sys.columns c ON c.object_id = a.object_id
JOIN sys.types t ON t.system_type_id = c.system_type_id AND t.system_type_id <> 231
WHERE b.name+'.'+a.name = @tbl
AND is_rowguidcol = 0 AND is_identity = 0 AND is_computed = 0
ORDER BY c.column_id
SET @sqlinsert = SUBSTRING(@sqlinsert,1,LEN(@sqlinsert)-1)
SET @sqlinsert = @sqlinsert + '
Insert Into ' + @tbl + ' ('
SELECT @sqlinsert = @sqlinsert + '
[' + c.name + '],'--c.column_id, c.name,c.system_type_id,t.name,c.max_length,t.max_length,c.*
FROM sys.tables a
JOIN sys.schemas b ON a.schema_id = b.schema_id
JOIN sys.columns c ON c.object_id = a.object_id
JOIN sys.types t ON t.system_type_id = c.system_type_id AND t.system_type_id <> 231
WHERE b.name+'.'+a.name = @tbl
AND is_rowguidcol = 0 AND is_identity = 0 AND is_computed = 0
ORDER BY c.column_id
SET @sqlinsert = SUBSTRING(@sqlinsert,1,LEN(@sqlinsert)-1)
SET @sqlinsert = @sqlinsert + ')
Values ('
SELECT @sqlinsert = @sqlinsert + '
@ins_' + c.name + ','--c.column_id, c.name,c.system_type_id,t.name,c.max_length,t.max_length,c.*
FROM sys.tables a
JOIN sys.schemas b ON a.schema_id = b.schema_id
JOIN sys.columns c ON c.object_id = a.object_id
JOIN sys.types t ON t.system_type_id = c.system_type_id AND t.system_type_id <> 231
WHERE b.name+'.'+a.name = @tbl
AND is_rowguidcol = 0 AND is_identity = 0 AND is_computed = 0
ORDER BY c.column_id
SET @sqlinsert = SUBSTRING(@sqlinsert,1,LEN(@sqlinsert)-1)
SET @sqlinsert = @sqlinsert + ')'
SELECT @sqlinsert
--SELECT * FROM sys.types
如果你的表没有涵盖专业,你可能需要更多的过滤器/案例来阅读系统视图。