Create Tables and Build inserts from Tables by using Mygeneration Templates(Sql Server)
生活随笔
收集整理的這篇文章主要介紹了
Create Tables and Build inserts from Tables by using Mygeneration Templates(Sql Server)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
asp.net下進行數據庫安裝與初始化化的例子 使用到了一個sql腳本文件,里面有創建表以及導入數據的部分,于是有朋友問是如何實現的,這里就簡單介紹下。
一開始,判斷表存在并刪除表的代碼是我自己寫的,基本做法如下:
????????private?System.Text.StringBuilder?sBuilder=new?System.Text.StringBuilder();
????????private?void?tt()
????????{
????????????try
????????????{
????????????????SqlConnection?conn=new?SqlConnection(txtConn.Text.Trim());
????????????????string?sql="select?name?from?dbo.sysobjects?where?OBJECTPROPERTY(id,?N'IsUserTable')?=?1?and?name?not?in?('dtproperties')";
????????????????SqlDataAdapter?adapter=new?SqlDataAdapter(sql,conn);
????????????????SqlCommandBuilder?sb=new?SqlCommandBuilder(adapter);
????????????????DataTable?dt=new?DataTable();
????????????????adapter.Fill(dt);????????????
????????????????for?(int?i?=?0;?i?<?dt.Rows.Count;?i++)
????????????????{
????????????????????CreateDropTableScript(dt.Rows[i][0].ToString());
????????????????}
????????????????txtResult.Text=sBuilder.ToString();
????????????????dt.Dispose();
????????????????conn.Close();
????????????}
????????????catch?(Exception?ex)
????????????{
????????????????
????????????}
????????}
????????private?void?CreateDropTableScript(string?tblName)
????????{
????????????Output("if?exists?(select?*?from?dbo.sysobjects?where?id?=?object_id(N'["+tblName+"]')?and?OBJECTPROPERTY(id,?N'IsUserTable')?=?1)");
????????????Output("drop?table?["+tblName+"]");
????????????Output("GO");????????
????????}
????????private?void?Output(string?s)
????????{????
????????????sBuilder.Append(s);
????????????sBuilder.Append(Environment.NewLine);
????????}
創建表和生成insert語句的部分是使用了Mygeneration的模板CreateTable.zenus和SQL_DataInserts.zenus.
后來為了省事,就改了CreateTable.zenus模板,在Create Table之前加入如下代碼:
if exists (select * from dbo.sysobjects where id = object_id(N'[<%=table.Name%>]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
?drop table [<%=table.Name%>]
GO?
修改后完整的Template Code代碼如下:
<%
Public?Class?GeneratedTemplateClass?GeneratedTemplate
????????????Inherits?DotNetScriptTemplate
????Public?Sub?New()Sub?New(context?As?ZeusContext)
????????MyBase.New(context)
????End?Sub
????'---------------------------------------------------
????'?Render()?is?where?you?want?to?write?your?logic????
????'---------------------------------------------------
????Public?Overrides?Sub?Render()Sub?Render
????
????????Dim?db?as?IDatabase
????????Dim?table?As?ITable
????????Dim?col?as?IColumn
????????Dim?IsFirst?As?Boolean
????????Dim?FK?As?IForeignKey
????????Dim?fkeys?As?New?HashTable
????????Dim?PKIndex?As?IIndex????
????
????????db?=?MyMeta.Databases(input.Item("cmbDatabase"))
????????'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
????????'''?Creating?basic?table?structur.
????????'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
????????For?Each?table?in?db.Tables
%>
if?exists?(select?*?from?dbo.sysobjects?where?id?=?object_id(N'[<%=table.Name%>]')?and?OBJECTPROPERTY(id,?N'IsUserTable')?=?1)
????drop?table?[<%=table.Name%>]
GO????
CREATE?TABLE?[<%=table.Name%>]?(
<%
????????????IsFirst?=?True
????????????output.incTab()
????????????For?Each?Col?in?table.Columns
????????????????If?IsFirst?=?False?Then
????????????????????output.write(?","?)
????????????????????output.writeln("")
????????????????End?If
????????????????output.autotab(?CreateColumnScript(?col?)?)
????????????????IsFirst?=?False
????????????Next
????????????output.decTab()
%>
)
GO
<%
????????????PKIndex?=?Nothing
????????????For?Each?FK?In?table.ForeignKeys
????????????????If?Not?fKeys.ContainsKey(?FK.Name?)?Then
????????????????????fKeys.Add(?FK.Name,?FK?)
????????????????End?If
????????????????If?PKIndex?Is?Nothing?AndAlso?FK.PrimaryTable.Name?=?table.Name?Then
????????????????????PKIndex?=?table.Indexes(?FK.PrimaryKeyName?)
????????????????End?If
????????????Next
????????????If?Not?PKIndex?Is?Nothing?Then
%>
ALTER?TABLE?[<%=table.Name%>]?WITH?NOCHECK?ADD?
????CONSTRAINT?[<%=PKIndex.Name%>]?PRIMARY?KEY??<%If?PKIndex.Clustered?Then?output.write("CLUSTERED")?%>
????(
<%
????????????????IsFirst?=?True
????????????????For?Each?col?In?PKIndex.Columns
????????????????????If?IsFirst?=?False?Then
????????????????????????output.write(",")
????????????????????????output.writeln("")
????????????????????End?If
????????
????????????????????output.autotab("["?+?col.Name?+?"]")
????????????????????IsFirst?=?False
????????????????Next
%>
????)??ON?[PRIMARY]?
GO
<%
????????????End?If
????????Next
????????For?Each?FK?In?fKeys.Values
%>
ALTER?TABLE?[<%=FK.ForeignTable.Name%>]?ADD?
????CONSTRAINT?[<%=FK.Name%>]?FOREIGN?KEY?
????(
????????<%
????????????IsFirst?=?True
????????????For?Each?col?In?FK.ForeignColumns
????????????????If?IsFirst?=?False?Then
????????????????????output.write(",")
????????????????????output.writeln("")
????????????????End?If
????????????????
????????????????output.autotab("["?+?col.Name?+?"]")
????????????????IsFirst?=?False
????????????Next
????????%>
????)?REFERENCES?[<%=FK.PrimaryTable.Name%>]?(
????????<%
????????????IsFirst?=?True
????????????For?Each?col?In?FK.PrimaryColumns
????????????????If?IsFirst?=?False?Then
????????????????????output.write(",")
????????????????????output.writeln("")
????????????????End?If
????????????????
????????????????output.autotab("["?+?col.Name?+?"]")
????????????????IsFirst?=?False
????????????Next
????????%>
????)?<%
????????If?FK.DeleteRule?<>?"NO?ACTION"?Then
????????????output.write(?"?ON?DELETE?"?+?FK.DeleteRule)
????????End?If
????????If?FK.UpdateRule?<>?"NO?ACTION"?Then
????????????output.write(?"?ON?UPDATE?"?+?FK.UpdateRule)
????????End?If
????%>
GO
<%
????????Next
????End?Sub
????Private?Function?CreateColumnScript()Function?CreateColumnScript(?ByVal?col?As?IColumn?)?As?String
????????Dim?retStr?As?String
????????retStr?=?"["?+?col.Name?+?"]?"?+?col.DataTypeNameComplete
????????If?col.IsAutoKey?Then
????????????retStr?+=?"?IDENTITY?(?"?+?col.AutoKeySeed.ToString()?+?","?+?col.AutoKeyIncrement.ToString()?+?"?)"
????????End?If
????????If?col.HasDefault?Then
????????????retStr?+=?"?DEFAULT?("?+?col.Default?+?")"
????????End?If
????????If?col.IsNullable?Then
????????????retStr?+=?"?NULL"
????????Else
????????????retStr?+=?"?NOT?NULL"
????????End?If
????????Return?retStr
????End?Function
End?Class
%>
當然生成insert語句的時候對Image字段無法處理。
既然Mygeneration可以很好地完成我要的工作(項目中需要做數據庫自動安裝部分,就是開頭提到的那個demo,當然還需要做很多完善的工作),我暫時也就懶得寫自己的代碼了,等有時間的時候也許我會重新寫下的。
注:安裝Mygeneration后,默認沒有上面所提到的兩個模板,你需要到mygeneration在線模板庫下載,你可以通過瀏覽網頁找到所需的模板,然后保存到指定目錄,當然下面的方法也許更讓你覺得方便很多:
download Templates from Mygeneration Online Template library
也許有朋友有更好的實現方法,希望能拿出來大家分享,謝謝!
一開始,判斷表存在并刪除表的代碼是我自己寫的,基本做法如下:
????????private?System.Text.StringBuilder?sBuilder=new?System.Text.StringBuilder();
????????private?void?tt()
????????{
????????????try
????????????{
????????????????SqlConnection?conn=new?SqlConnection(txtConn.Text.Trim());
????????????????string?sql="select?name?from?dbo.sysobjects?where?OBJECTPROPERTY(id,?N'IsUserTable')?=?1?and?name?not?in?('dtproperties')";
????????????????SqlDataAdapter?adapter=new?SqlDataAdapter(sql,conn);
????????????????SqlCommandBuilder?sb=new?SqlCommandBuilder(adapter);
????????????????DataTable?dt=new?DataTable();
????????????????adapter.Fill(dt);????????????
????????????????for?(int?i?=?0;?i?<?dt.Rows.Count;?i++)
????????????????{
????????????????????CreateDropTableScript(dt.Rows[i][0].ToString());
????????????????}
????????????????txtResult.Text=sBuilder.ToString();
????????????????dt.Dispose();
????????????????conn.Close();
????????????}
????????????catch?(Exception?ex)
????????????{
????????????????
????????????}
????????}
????????private?void?CreateDropTableScript(string?tblName)
????????{
????????????Output("if?exists?(select?*?from?dbo.sysobjects?where?id?=?object_id(N'["+tblName+"]')?and?OBJECTPROPERTY(id,?N'IsUserTable')?=?1)");
????????????Output("drop?table?["+tblName+"]");
????????????Output("GO");????????
????????}
????????private?void?Output(string?s)
????????{????
????????????sBuilder.Append(s);
????????????sBuilder.Append(Environment.NewLine);
????????}
創建表和生成insert語句的部分是使用了Mygeneration的模板CreateTable.zenus和SQL_DataInserts.zenus.
后來為了省事,就改了CreateTable.zenus模板,在Create Table之前加入如下代碼:
if exists (select * from dbo.sysobjects where id = object_id(N'[<%=table.Name%>]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
?drop table [<%=table.Name%>]
GO?
修改后完整的Template Code代碼如下:
<%
Public?Class?GeneratedTemplateClass?GeneratedTemplate
????????????Inherits?DotNetScriptTemplate
????Public?Sub?New()Sub?New(context?As?ZeusContext)
????????MyBase.New(context)
????End?Sub
????'---------------------------------------------------
????'?Render()?is?where?you?want?to?write?your?logic????
????'---------------------------------------------------
????Public?Overrides?Sub?Render()Sub?Render
????
????????Dim?db?as?IDatabase
????????Dim?table?As?ITable
????????Dim?col?as?IColumn
????????Dim?IsFirst?As?Boolean
????????Dim?FK?As?IForeignKey
????????Dim?fkeys?As?New?HashTable
????????Dim?PKIndex?As?IIndex????
????
????????db?=?MyMeta.Databases(input.Item("cmbDatabase"))
????????'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
????????'''?Creating?basic?table?structur.
????????'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
????????For?Each?table?in?db.Tables
%>
if?exists?(select?*?from?dbo.sysobjects?where?id?=?object_id(N'[<%=table.Name%>]')?and?OBJECTPROPERTY(id,?N'IsUserTable')?=?1)
????drop?table?[<%=table.Name%>]
GO????
CREATE?TABLE?[<%=table.Name%>]?(
<%
????????????IsFirst?=?True
????????????output.incTab()
????????????For?Each?Col?in?table.Columns
????????????????If?IsFirst?=?False?Then
????????????????????output.write(?","?)
????????????????????output.writeln("")
????????????????End?If
????????????????output.autotab(?CreateColumnScript(?col?)?)
????????????????IsFirst?=?False
????????????Next
????????????output.decTab()
%>
)
GO
<%
????????????PKIndex?=?Nothing
????????????For?Each?FK?In?table.ForeignKeys
????????????????If?Not?fKeys.ContainsKey(?FK.Name?)?Then
????????????????????fKeys.Add(?FK.Name,?FK?)
????????????????End?If
????????????????If?PKIndex?Is?Nothing?AndAlso?FK.PrimaryTable.Name?=?table.Name?Then
????????????????????PKIndex?=?table.Indexes(?FK.PrimaryKeyName?)
????????????????End?If
????????????Next
????????????If?Not?PKIndex?Is?Nothing?Then
%>
ALTER?TABLE?[<%=table.Name%>]?WITH?NOCHECK?ADD?
????CONSTRAINT?[<%=PKIndex.Name%>]?PRIMARY?KEY??<%If?PKIndex.Clustered?Then?output.write("CLUSTERED")?%>
????(
<%
????????????????IsFirst?=?True
????????????????For?Each?col?In?PKIndex.Columns
????????????????????If?IsFirst?=?False?Then
????????????????????????output.write(",")
????????????????????????output.writeln("")
????????????????????End?If
????????
????????????????????output.autotab("["?+?col.Name?+?"]")
????????????????????IsFirst?=?False
????????????????Next
%>
????)??ON?[PRIMARY]?
GO
<%
????????????End?If
????????Next
????????For?Each?FK?In?fKeys.Values
%>
ALTER?TABLE?[<%=FK.ForeignTable.Name%>]?ADD?
????CONSTRAINT?[<%=FK.Name%>]?FOREIGN?KEY?
????(
????????<%
????????????IsFirst?=?True
????????????For?Each?col?In?FK.ForeignColumns
????????????????If?IsFirst?=?False?Then
????????????????????output.write(",")
????????????????????output.writeln("")
????????????????End?If
????????????????
????????????????output.autotab("["?+?col.Name?+?"]")
????????????????IsFirst?=?False
????????????Next
????????%>
????)?REFERENCES?[<%=FK.PrimaryTable.Name%>]?(
????????<%
????????????IsFirst?=?True
????????????For?Each?col?In?FK.PrimaryColumns
????????????????If?IsFirst?=?False?Then
????????????????????output.write(",")
????????????????????output.writeln("")
????????????????End?If
????????????????
????????????????output.autotab("["?+?col.Name?+?"]")
????????????????IsFirst?=?False
????????????Next
????????%>
????)?<%
????????If?FK.DeleteRule?<>?"NO?ACTION"?Then
????????????output.write(?"?ON?DELETE?"?+?FK.DeleteRule)
????????End?If
????????If?FK.UpdateRule?<>?"NO?ACTION"?Then
????????????output.write(?"?ON?UPDATE?"?+?FK.UpdateRule)
????????End?If
????%>
GO
<%
????????Next
????End?Sub
????Private?Function?CreateColumnScript()Function?CreateColumnScript(?ByVal?col?As?IColumn?)?As?String
????????Dim?retStr?As?String
????????retStr?=?"["?+?col.Name?+?"]?"?+?col.DataTypeNameComplete
????????If?col.IsAutoKey?Then
????????????retStr?+=?"?IDENTITY?(?"?+?col.AutoKeySeed.ToString()?+?","?+?col.AutoKeyIncrement.ToString()?+?"?)"
????????End?If
????????If?col.HasDefault?Then
????????????retStr?+=?"?DEFAULT?("?+?col.Default?+?")"
????????End?If
????????If?col.IsNullable?Then
????????????retStr?+=?"?NULL"
????????Else
????????????retStr?+=?"?NOT?NULL"
????????End?If
????????Return?retStr
????End?Function
End?Class
%>
當然生成insert語句的時候對Image字段無法處理。
既然Mygeneration可以很好地完成我要的工作(項目中需要做數據庫自動安裝部分,就是開頭提到的那個demo,當然還需要做很多完善的工作),我暫時也就懶得寫自己的代碼了,等有時間的時候也許我會重新寫下的。
注:安裝Mygeneration后,默認沒有上面所提到的兩個模板,你需要到mygeneration在線模板庫下載,你可以通過瀏覽網頁找到所需的模板,然后保存到指定目錄,當然下面的方法也許更讓你覺得方便很多:
download Templates from Mygeneration Online Template library
也許有朋友有更好的實現方法,希望能拿出來大家分享,謝謝!
總結
以上是生活随笔為你收集整理的Create Tables and Build inserts from Tables by using Mygeneration Templates(Sql Server)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JEECG v3.0.beta发布,基于
- 下一篇: MySQL进阶篇(01):基于多个维度,