简体   繁体   中英

How to automatically generate script using command line in SQL Server?

In SQL Server Management Studio, there is a "Generate and Publish Scripts Wizard" context menu option that automatically generates the insert statement script for the table's data.

In my case, I have access to only query on a database using command line. Meaning I am unable to access the "Generate and Publish Scripts Wizard".

Is it possible to achieve something similar using pure SQL or T-SQL command line?

That is a basic SQL build the insert based on system views:

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

Perhaps you may need some more filters/cases reading the sys views if your tables have specialties not covered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM