SQL Server 데이터베이스 의 표 이름,필드 비교

머리말
프로젝트 에 서 는 일반적으로 테스트 환경(QAS),생산 환경(PRD)으로 나 뉘 는데,우리 의 프로젝트 가 주기 적 으로 긴 업 데 이 트 를 거 친 후에 우리 가 생산 환경 에 발표 할 때 가장 중요 한 임 무 는 새로 추 가 된 표,필드 를 생산 데이터 베이스 에 업데이트 하 는 것 이다.우리 가 업 데 이 트 를 발표 할 때 어떤 변경 을 했 는 지 기억 하기 어 려 울 때 가 많다.
물론 1.EF Code First 에 history 기록 이 있다 고 말 하 는 사람 도 있 습 니 다.이것 은 방법 입 니 다.믿 을 수 있 습 니까?미 덥 지 못 하 다.Code First 를 사용 하 더 라 도 데이터 베 이 스 를 직접 고 친 것 은 나 뿐만 이 아니 라 고 믿는다.
 2.실체 류 변경 기록 을 보 는 것 도 방법 이다.그럼 DB First 를 썼 다 면?물론 볼 수도 있 지만 귀 찮 습 니 다.
 3.개발 과정 에서 데이터베이스 에 대한 변경 사항 을 기록한다.그 랬 던 것 도 나 뿐만 이 아니 었 을 거 야.수 동 개 머리
  。。。。。
점심 시간 에 다른 프로젝트 가 다음 달 에 업 데 이 트 될 거 라 고 생각 하고 N 이 많은 것 을 바 꿨 어 요.그때 데이터 베 이 스 를 어떻게 업데이트 할 까요?두 버 전의 데이터베이스,표 이름,필드,필드 형식의 차 이 를 비교 하 는 도 구 를 쓰 려 고 합 니 다.
한다 고 하면 한다.
콘 솔 프로그램 은 현재 새로 추 가 된 것 과 수정(SQL Server)만 비교 할 수 있 습 니 다.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
namespace EFGetTable
{
 class Program
 {
  static void Main(string[] args)
  {
   string prdconnectionstring = "Data Source=localhost;initial catalog=ttPRD;user id=sa;password=password;MultipleActiveResultSets=True";

   var prd = GetTableNames(prdconnectionstring);

   string qasconnectionstring = "Data Source=localhost;initial catalog=ttqas;user id=sa;password=password;MultipleActiveResultSets=True";

   var qas = GetTableNames(qasconnectionstring);

   CompareTable(prd, qas);
  }

  public static List<TableInfo> GetTableNames(string connectionstr)
  {

   var tableresult = new List<TableInfo>();
   string sqlTableName = "Select * From Information_Schema.Tables";
   using (SqlConnection connection = new SqlConnection(connectionstr))
   {
    using (SqlCommand cmd = new SqlCommand(sqlTableName, connection))
    {
     try
     {
      connection.Open();
      SqlDataReader dr = cmd.ExecuteReader();//

      while (dr.Read())
      {
       //   
       TableInfo table = new TableInfo();

       table.TableName = dr["Table_Name"].ToString();


       table.columns.AddRange(GetColumnNamesByTable(dr["Table_Name"].ToString(), connection));
       tableresult.Add(table);
      }


      connection.Close();

     }
     catch (System.Data.SqlClient.SqlException e)
     {
      Console.ForegroundColor = ConsoleColor.Red;
      Console.Error.WriteLine(e.Message);
      connection.Close();
     }
    }

    return tableresult;
   }


  }
  public static List<CloumnInfo> GetColumnNamesByTable(string tableName, SqlConnection connection)
  {

   var Columnresults = new List<CloumnInfo>();
   string sqlcolum = $"Select * From Information_Schema.Columns t Where t.Table_Name =\'{tableName}\'";

   using (SqlCommand cmd = new SqlCommand(sqlcolum, connection))
   {

    SqlDataReader dr = cmd.ExecuteReader();//

    while (dr.Read())
    {
     //   
     CloumnInfo column = new CloumnInfo();
     column.CloumnName = dr["Column_name"].ToString();
     column.DateType = dr["DATA_TYPE"].ToString() + dr["CHARACTER_MAXIMUM_LENGTH"].ToString();
     Columnresults.Add(column);
    }

    return Columnresults;

   }
  }
  public static void CompareTable(List<TableInfo> prd, List<TableInfo> qas)
  {
   foreach (var p in qas)
   {
    var tablequery = prd.AsQueryable().Where(t => t.TableName.Equals(p.TableName));
    if (!tablequery.Any())
    {
     Console.WriteLine($"New Created Table {p.TableName}");
     continue;
    }
    else
    {
     var querytable = tablequery.FirstOrDefault();
     p.columns.ForEach(c =>
     {
      var Cloumnquery = querytable.columns.Select(cc => cc.CloumnName).Contains(c.CloumnName);

      if (!Cloumnquery)
      {
       Console.WriteLine($"New add cloumn: {c.CloumnName} on Table {p.TableName}");

      }

      else
      {
       var querycloumn = querytable.columns.Where(qt => qt.CloumnName.Equals(c.CloumnName)).FirstOrDefault();
       if (!querycloumn.DateType.Equals(c.DateType))
       {
        Console.WriteLine($"DateType Different: cloumn: {c.CloumnName} , {querycloumn.DateType}==>{c.DateType} on Table {p.TableName}");

       }
      }
     });
    }
   }
  }

 }

 public class TableInfo
 {
  public TableInfo()
  {
   columns = new List<CloumnInfo>();
  }
  public string TableName { get; set; }
  public List<CloumnInfo> columns { get; set; }
 }

 public class CloumnInfo
 {
  public string CloumnName { get; set; }
  public string DateType { get; set; }

 }
}
테스트 결과

총결산
이상 은 이 글 의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가 치 를 가지 기 를 바 랍 니 다.여러분 의 저희 에 대한 지지 에 감 사 드 립 니 다.

좋은 웹페이지 즐겨찾기