In SQL Server, how do I generate a CREATE TABLE statement for a given table?

前端 未结 16 2475
离开以前
离开以前 2020-11-22 11:34

I\'ve spent a good amount of time coming up with solution to this problem, so in the spirit of this post, I\'m posting it here, since I think it might be useful to others. <

16条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 11:39

    There is a Powershell script buried in the msdb forums that will script all the tables and related objects:

    # Script all tables in a database
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") 
        | out-null
    
    $s = new-object ('Microsoft.SqlServer.Management.Smo.Server') ''
    $db = $s.Databases['']
    
    $scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($s)
    $scrp.Options.AppendToFile = $True
    $scrp.Options.ClusteredIndexes = $True
    $scrp.Options.DriAll = $True
    $scrp.Options.ScriptDrops = $False
    $scrp.Options.IncludeHeaders = $False
    $scrp.Options.ToFileOnly = $True
    $scrp.Options.Indexes = $True
    $scrp.Options.WithDependencies = $True
    $scrp.Options.FileName = 'C:\Temp\.SQL'
    
    foreach($item in $db.Tables) { $tablearray+=@($item) }
    $scrp.Script($tablearray)
    
    Write-Host "Scripting complete"
    

提交回复
热议问题