복붙노트

[SQL] 생성 SQL 코드 프로그램

SQL

생성 SQL 코드 프로그램

내가 스크립트를 수동으로 통해 마우스 오른쪽 버튼을 클릭 데이터베이스에서 작업 메뉴에서 스크립트를 생성 생성 한.

이제 내 문제는 C # 코드를 통해 해당 스크립트를 생성하는 것입니다 ...

내 질문은

여러분의 소중한 제안과 명령을 기다리는 중.

해결법

  1. ==============================

    1.이미 언급 한 것, 당신이 할 SMO를 사용 CAS, 여기에, 나는 몇 가지 옵션을 언급 한 스크립트에 데이터베이스를 C #을 사용하는 예이지만 @ 데이비드 브라 반트의 포스트에서와 같이, 당신은 많은 옵션의 값을 지정할 수 있습니다 .

    이미 언급 한 것, 당신이 할 SMO를 사용 CAS, 여기에, 나는 몇 가지 옵션을 언급 한 스크립트에 데이터베이스를 C #을 사용하는 예이지만 @ 데이비드 브라 반트의 포스트에서와 같이, 당신은 많은 옵션의 값을 지정할 수 있습니다 .

    public string ScriptDatabase()
    {
          var sb = new StringBuilder();
    
          var server = new Server(@"ServerName");
          var databse = server.Databases["DatabaseName"];
    
          var scripter = new Scripter(server);
          scripter.Options.ScriptDrops = false;
          scripter.Options.WithDependencies = true;
          scripter.Options.IncludeHeaders = true;
          //And so on ....
    
    
          var smoObjects = new Urn[1];
          foreach (Table t in databse.Tables)
          {
              smoObjects[0] = t.Urn;
              if (t.IsSystemObject == false)
              {
                  StringCollection sc = scripter.Script(smoObjects);
    
                  foreach (var st in sc)
                  {
                      sb.Append(st);
                  }
               }
           }
                return sb.ToString();
     }
    

    이 링크는 저장 프로 시저를 얻고 스크립팅 도움이 될 수 있습니다

  2. ==============================

    2.당신은 기본적으로 SQL Server 엔터프라이즈 관리자에서 사용할 수있는 모든 기능을 구현하기위한 SQL SMO를 사용할 수 있습니다. 여기에 좋은 튜토리얼이있다.

    당신은 기본적으로 SQL Server 엔터프라이즈 관리자에서 사용할 수있는 모든 기능을 구현하기위한 SQL SMO를 사용할 수 있습니다. 여기에 좋은 튜토리얼이있다.

    편집 : PowerShell에서 SMO를 사용하는 예제

    function SQL-Script-Database
    {
        <#
        .SYNOPSIS
        Script all database objects for the given database.
    
        .DESCRIPTION
        This  function scripts all database objects  (i.e.: tables,  views, stored
        procedures,  and user defined functions) for the specified database on the
        the given server\instance. It creates a subdirectory per object type under 
        the path specified.
    
        .PARAMETER savePath
        The root path where to save object definitions.
    
        .PARAMETER database
        The database to script (default = $global:DatabaseName)
    
        .PARAMETER DatabaseServer 
        The database server to be used (default: $global:DatabaseServer).
    
        .PARAMETER InstanceName 
        The instance name to be used (default: $global:InstanceName).
    
        .EXAMPLE
        SQL-Script-Database c:\temp AOIDB
        #>
    
        param (
            [parameter(Mandatory = $true)][string] $savePath,
            [parameter(Mandatory = $false)][string] $database = $global:DatabaseName,
            [parameter(Mandatory = $false)][string] $DatabaseServer = $global:DatabaseServer,
            [parameter(Mandatory = $false)][string] $InstanceName = $global:InstanceName
        )
    
        try
        {
            if (!$DatabaseServer -or !$InstanceName)
                { throw "`$DatabaseServer or `$InstanceName variable is not properly initialized" }
    
            $ServerInstance = SQL-Get-Server-Instance $DatabaseServer $InstanceName
    
            [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
    
            $s = New-Object Microsoft.SqlServer.Management.Smo.Server($ServerInstance)
            $db = $s.databases[$database]
    
            $objects = $db.Tables
            $objects += $db.Views
            $objects += $db.StoredProcedures
            $objects += $db.UserDefinedFunctions
    
            $scripter = New-Object ('Microsoft.SqlServer.Management.Smo.Scripter') ($s)
    
            $scripter.Options.AnsiFile = $true
            $scripter.Options.IncludeHeaders = $false
            $scripter.Options.ScriptOwner = $false
            $scripter.Options.AppendToFile = $false
            $scripter.Options.AllowSystemobjects = $false
            $scripter.Options.ScriptDrops = $false
            $scripter.Options.WithDependencies = $false
            $scripter.Options.SchemaQualify = $false
            $scripter.Options.SchemaQualifyForeignKeysReferences = $false
            $scripter.Options.ScriptBatchTerminator = $false
    
            $scripter.Options.Indexes = $true
            $scripter.Options.ClusteredIndexes = $true
            $scripter.Options.NonClusteredIndexes = $true
            $scripter.Options.NoCollation = $true
    
            $scripter.Options.DriAll = $true
            $scripter.Options.DriIncludeSystemNames = $false
    
            $scripter.Options.ToFileOnly = $true
            $scripter.Options.Permissions = $true
    
            foreach ($o in $objects | where {!($_.IsSystemObject)}) 
            {
                $typeFolder=$o.GetType().Name 
    
                if (!(Test-Path -Path "$savepath\$typeFolder")) 
                    { New-Item -Type Directory -name "$typeFolder"-path "$savePath" | Out-Null }
    
                $file = $o -replace "\[|\]"
                $file = $file.Replace("dbo.", "")
    
                $scripter.Options.FileName = "$savePath\$typeFolder\$file.sql"
                $scripter.Script($o)
            }
        }
    
        catch
        {
            Util-Log-Error "`t`t$($MyInvocation.InvocationName): $_"
        }
    }
    
  3. ==============================

    3.@Sami의 답변에 따라

    @Sami의 답변에 따라

    나는 당신의 데이터베이스에 대한 모든 스크립트를 생성합니다이 간단한 기능을 만들 수 있습니다 (테이블, 뷰, 저장 프로 시저, 사용자 및 UserDefinedFunctions)

    첫째 : 필수 어셈블리를 가져옵니다

    당신에 대한 참조를 추가해야합니다 :

    Microsoft.SqlServer.ConnectionInfo.dll

    Mitsrosoft.Syalserver.Smo.dl

    Microsoft.SqlServer.Management.Sdk.Sfc.dll

    Microsoft.SqlServer.SqlEnum.dll

    둘째 :이 기능을 사용

      public static string ScriptDatabase() 
    {
        // For Me Server is ".\SQLExpress" You may have changed
        Server myServer = new Server(@".\SQLExpress");
        Scripter scripter = new Scripter(myServer);
    
        //Databas1 is your database Name Thats Changable
    
        Database myAdventureWorks = myServer.Databases["MyDBName"];
        /* With ScriptingOptions you can specify different scripting  
        * options, for example to include IF NOT EXISTS, DROP  
        * statements, output location etc*/
        ScriptingOptions scriptOptions = new ScriptingOptions();
        scriptOptions.ScriptDrops = true;
       // scriptOptions.ScriptData = true;
        scriptOptions.ScriptSchema = true;
    
    
        scriptOptions.IncludeIfNotExists = true;
        string scrs = "";
        string tbScr = "";
        foreach (Table myTable in myAdventureWorks.Tables)
        {
            /* Generating IF EXISTS and DROP command for tables */
            StringCollection tableScripts = myTable.Script(scriptOptions);
            foreach (string script in tableScripts)
                scrs += script + "\n\n";
    
            /* Generating CREATE TABLE command */
            tableScripts = myTable.Script();
            foreach (string script in tableScripts)
                tbScr += script + "\n\n";
        }
    
    
        foreach (StoredProcedure mySP in myAdventureWorks.StoredProcedures)
        {
            /* Generating IF EXISTS and DROP command for StoredProcedures */
            StringCollection tableScripts = mySP.Script(scriptOptions);
            foreach (string script in tableScripts)
                scrs += script + "\n\n";
    
            /* Generating CREATE StoredProcedure command */
            tableScripts = mySP.Script(scriptOptions);
            foreach (string script in tableScripts)
                tbScr += script + "\n\n";
        }
    
        foreach (View myView in myAdventureWorks.Views)
        {
            /* Generating IF EXISTS and DROP command for Views */
            StringCollection tableScripts = myView.Script(scriptOptions);
            foreach (string script in tableScripts)
                scrs += script + "\n\n";
    
            /* Generating CREATE Views command */
            tableScripts = myView.Script(scriptOptions);
            foreach (string script in tableScripts)
                tbScr += script+"\n\n";
        }
    
    
        foreach (Microsoft.SqlServer.Management.Smo.User user in myAdventureWorks.Users)
        {
            /* Generating IF EXISTS and DROP command for Users */
            StringCollection tableScripts = user.Script(scriptOptions);
            foreach (string script in tableScripts)
                scrs += script+"\n\n";
    
            /* Generating CREATE Users command */
            tableScripts = user.Script(scriptOptions);
            foreach (string script in tableScripts)
                scrs += script + "\n\n";
        }
    
    
    
        foreach (Microsoft.SqlServer.Management.Smo.UserDefinedFunction userF in myAdventureWorks.UserDefinedFunctions)
        {
            /* Generating IF EXISTS and DROP command for UserDefinedFunctions */
            StringCollection tableScripts = userF.Script(scriptOptions);
            foreach (string script in tableScripts)
                scrs += script + "\n\n";
    
            /* Generating CREATE UserDefinedFunction command */
            tableScripts = userF.Script(scriptOptions);
            foreach (string script in tableScripts)
                scrs += script + "\n\n";
        } 
    
        // For WinForms
        return (scrs + "\n\n" + tbScr);
        //For Console
        //Console.WriteLine(scrs + "\n\n" + tbScr);
    }
    
  4. ==============================

    4.난 그냥 C #에서이 작업을 수행하는 명령 줄 프로그램을 작성하는 위의 답변을 사용하고 나는 위의 대답에 약간의 확장 거라고 생각했다.

    난 그냥 C #에서이 작업을 수행하는 명령 줄 프로그램을 작성하는 위의 답변을 사용하고 나는 위의 대답에 약간의 확장 거라고 생각했다.

    당신이 잘 스키마로 데이터를 출력하려는 ​​경우는 사용이 필요합니다

    scripter.EnumScript(something);
    //instead of 
    scripter.Script(something);
    

    IncludeData 옵션 만 확인 스크립트 방법이 설정된 경우 예외가 발생합니다,하지만 당신은 사용할 수있는 권리 방법은 무엇인지 알아 구글에 얻을 수있다! 재미있는 API 디자인!

    다음과 같이 데이터베이스에 관련 목록은 다음과 같습니다 :

            database.Tables
            database.Schemas
            database.Views
            database.StoredProcedures
            database.UserDefinedFunctions
            database.Users
            database.Roles
            database.Sequences
    

    그 철저한되지 않을 수도 있지만.

    시스템 개체를 제거하기

    이러한 객체의리스트를 IEnumerable을하지만 모든 사용자 정의 종류되지는 IEnumerable 당신이 그들에 LINQ하지 않을 수 있습니다. 이것은 또한 당신이 유형을 나가 그들과 사용의 foreach의 암시 적 캐스트에 무엇인지 알아해야 의미합니다. 나는 C #에서하지만이 물건은 아마 프레임 워크 (2)를 목표로 생각하기 전에 해당 사용되지 않는 것입니다.

    그들 중 많은도 IsSystemObject라는 속성을 가지고 있지만,이 인터페이스를 구현하지 않습니다. 이 모든 시스템 개체를 제거하는 진짜 고통이 될 것입니다하지만 당신은 하나 모두 다음과 같은 옵션을 설정하여 급습 하락을 추려 수있는 것처럼 처음에는 본다 :

    options.AllowSystemObjects = false;
    

    이것은 당신이 손으로 시스템 것들을해야 할 사람들을 위해 역할을 제외한 모든 작동 :

            foreach (DatabaseRole role in database.Roles)
            {
                if(role.IsFixedRole)
                    continue;
    
                list.Add(role);
            }
    

    출력 객체 추가

    내가 사용하는 프로세스는 UrnCollection을 만든 다음 컬렉션에 다른 목록을 추가했다. 이 같이 :

            var list = new UrnCollection();
    
            foreach (Schema schema in database.Schemas)
                list.Add(schema.Urn);
            //... more of these
    
            scripter.EnumScript(list);
    

    옵션

    거기에서 세트 옵션은 당신이 필요로하는 출력을 다시 알아낼 필요가있다. 염두에 두어야 할 몇 가지 :

    등 외래 키를 얻는 방법에 대한 자세한 내용은이 게시물을 참조하십시오.

    건강 경고

    나는 백업 생각으로 데이터베이스를 복사하고 내가 원하는 일을하지 않을 복원하는 방법으로이보고 시작했다. 많은 문제에 SMO 경로 아래로 꽤 먼 길을 가서 실행 한 후 나는 재평가의 비트를했다 및 백업 발견하고 그 사용 사례에 대한 많은 간단 복원합니다.

  5. ==============================

    5.잘만되면 당신과 곧 사람을 안내 할 것입니다.

    잘만되면 당신과 곧 사람을 안내 할 것입니다.

    당신은 다음과 같은 필수 네임 스페이스를 포함하는 프로젝트에 네 개의 참조를 다음과 같은 추가해야

    참조를 추가하려면

    참조 Microsoft.SqlServer.Smo.dll

    네임 스페이스

    using System.Data.SqlClient;
    using System.Collections.Specialized;
    using Microsoft.SqlServer.Management.Smo;
    

    이제 어떤 기능이나 버튼 클릭 이벤트에 다음 코드를 사용하여

            // For Me Server is ".\SQLExpress" You may have changed
            Server myServer = new Server(@".\SQLExpress");
            Scripter scripter = new Scripter(myServer);
    
            //Databas1 is your database Name Thats Changable
    
            Database myAdventureWorks = myServer.Databases["Database1"];
            /* With ScriptingOptions you can specify different scripting  
            * options, for example to include IF NOT EXISTS, DROP  
            * statements, output location etc*/
            ScriptingOptions scriptOptions = new ScriptingOptions();
            scriptOptions.ScriptDrops = true;
            scriptOptions.IncludeIfNotExists = true;
            string scrs = "";
            string tbScr = "";
            foreach (Table myTable in myAdventureWorks.Tables)
            {
                /* Generating IF EXISTS and DROP command for tables */
                StringCollection tableScripts = myTable.Script(scriptOptions);
                foreach (string script in tableScripts)
                    scrs += script;
    
                /* Generating CREATE TABLE command */
                tableScripts = myTable.Script();
                foreach (string script in tableScripts)
                    tbScr += script;
            }
            // For WinForms
            MessageBox.Show(scrs + "\n\n" + tbScr);
            //For Console
            //Console.WriteLine(scrs + "\n\n" + tbScr);
    

    그것은 데이비드 브라 반트와 SO의 위의 링크에 의해 (위) http://www.mssqltips.com/sqlservertip/1833/generate-scripts-for-database-objects-with-smo-for-sql-server/ 대답을 참여

    코드 블록이 사용됩니다. 지금 당신은 다른 사람을 사용뿐만 아니라 수 있습니다

    나는 MYSERVER가 찾을 수 없습니다하지만 위의 코드에서뿐만 아니라 해결됩니다.

  6. from https://stackoverflow.com/questions/12140422/generating-sql-code-programmatically by cc-by-sa and MIT license