动态创建SQL Server数据库、表、存储过程

server|创建|存储过程|动态|数据|数据库

下面是利用SQL语句创建数据库、表、存储过程、视图、索引、规则、修改表、查看数据等的方法。所要增加的控件如下:

Imports System.Data
Imports System.Data.SqlClient

Public Class Form1
  Inherits System.Windows.Forms.Form
  Private ConnectionString As String = "Data Source=.;Initial Catalog=;User Id=sa;Password=;"
  Private reader As SqlDataReader = Nothing
  Private conn As SqlConnection = Nothing
  Private cmd As SqlCommand = Nothing
  Private AlterTableBtn As System.Windows.Forms.Button
  Private sql As String = Nothing
  Private CreateOthersBtn As System.Windows.Forms.Button

#Region " Windows 窗体设计器生成的代码 "
  '窗体重写处置以清理组件列表。
  Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
    If disposing Then
      If Not (components Is Nothing) Then
        components.Dispose()
      End If
    End If
    MyBase.Dispose(disposing)
  End Sub
  Public Sub New()
    MyBase.New()
    InitializeComponent()
  End Sub
  Private components As System.ComponentModel.IContainer
  Friend WithEvents DataGrid1 As System.Windows.Forms.DataGrid
  Friend WithEvents CreateDBBtn As System.Windows.Forms.Button
  Friend WithEvents CreateTableBtn As System.Windows.Forms.Button
  Friend WithEvents CreateSPBtn As System.Windows.Forms.Button
  Friend WithEvents CreateViewBtn As System.Windows.Forms.Button
  Friend WithEvents btnAlterTable As System.Windows.Forms.Button
  Friend WithEvents btnCreateOthers As System.Windows.Forms.Button
  Friend WithEvents btnDropTable As System.Windows.Forms.Button
  Friend WithEvents btnViewData As System.Windows.Forms.Button
  Friend WithEvents btnViewSP As System.Windows.Forms.Button
  Friend WithEvents btnViewView As System.Windows.Forms.Button
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
    Me.CreateDBBtn = New System.Windows.Forms.Button()
    Me.CreateTableBtn = New System.Windows.Forms.Button()
    Me.CreateSPBtn = New System.Windows.Forms.Button()
    Me.CreateViewBtn = New System.Windows.Forms.Button()
    Me.btnAlterTable = New System.Windows.Forms.Button()
    Me.btnCreateOthers = New System.Windows.Forms.Button()
    Me.btnDropTable = New System.Windows.Forms.Button()
    Me.btnViewData = New System.Windows.Forms.Button()
    Me.btnViewSP = New System.Windows.Forms.Button()
    Me.btnViewView = New System.Windows.Forms.Button()
    Me.DataGrid1 = New System.Windows.Forms.DataGrid()
    CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).BeginInit()
    Me.SuspendLayout()
    '
    'CreateDBBtn
    '
    Me.CreateDBBtn.Location = New System.Drawing.Point(19, 9)
    Me.CreateDBBtn.Name = "CreateDBBtn"
    Me.CreateDBBtn.Size = New System.Drawing.Size(104, 23)
    Me.CreateDBBtn.TabIndex = 0
    Me.CreateDBBtn.Text = "创建数据库"
    '
    'CreateTableBtn
    '
    Me.CreateTableBtn.Location = New System.Drawing.Point(139, 9)
    Me.CreateTableBtn.Name = "CreateTableBtn"
    Me.CreateTableBtn.TabIndex = 1
    Me.CreateTableBtn.Text = "创建表"
    '
    'CreateSPBtn
    '
    Me.CreateSPBtn.Location = New System.Drawing.Point(230, 9)
    Me.CreateSPBtn.Name = "CreateSPBtn"
    Me.CreateSPBtn.Size = New System.Drawing.Size(104, 23)
    Me.CreateSPBtn.TabIndex = 2
    Me.CreateSPBtn.Text = "创建存储过程"
    '
    'CreateViewBtn
    '
    Me.CreateViewBtn.Location = New System.Drawing.Point(350, 9)
    Me.CreateViewBtn.Name = "CreateViewBtn"
    Me.CreateViewBtn.TabIndex = 3
    Me.CreateViewBtn.Text = "创建视图"
    '
    'btnAlterTable
    '
    Me.btnAlterTable.Location = New System.Drawing.Point(441, 9)
    Me.btnAlterTable.Name = "btnAlterTable"
    Me.btnAlterTable.TabIndex = 4
    Me.btnAlterTable.Text = "修改表"
    '
    'btnCreateOthers
    '
    Me.btnCreateOthers.Location = New System.Drawing.Point(17, 43)
    Me.btnCreateOthers.Name = "btnCreateOthers"
    Me.btnCreateOthers.Size = New System.Drawing.Size(104, 23)
    Me.btnCreateOthers.TabIndex = 5
    Me.btnCreateOthers.Text = "创建规则和索引"
    '
    'btnDropTable
    '
    Me.btnDropTable.Location = New System.Drawing.Point(138, 43)
    Me.btnDropTable.Name = "btnDropTable"
    Me.btnDropTable.TabIndex = 6
    Me.btnDropTable.Text = "删除表"
    '
    'btnViewData
    '
    Me.btnViewData.Location = New System.Drawing.Point(351, 43)
    Me.btnViewData.Name = "btnViewData"
    Me.btnViewData.TabIndex = 7
    Me.btnViewData.Text = "查看数据"
    '
    'btnViewSP
    '
    Me.btnViewSP.Location = New System.Drawing.Point(230, 43)
    Me.btnViewSP.Name = "btnViewSP"
    Me.btnViewSP.Size = New System.Drawing.Size(104, 23)
    Me.btnViewSP.TabIndex = 8
    Me.btnViewSP.Text = "查看存储过程"
    '
    'btnViewView
    '
    Me.btnViewView.Location = New System.Drawing.Point(443, 43)
    Me.btnViewView.Name = "btnViewView"
    Me.btnViewView.TabIndex = 9
    Me.btnViewView.Text = "查看视图"
    '
    'DataGrid1
    '
    Me.DataGrid1.DataMember = ""
    Me.DataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText
    Me.DataGrid1.Location = New System.Drawing.Point(20, 76)
    Me.DataGrid1.Name = "DataGrid1"
    Me.DataGrid1.Size = New System.Drawing.Size(500, 183)
    Me.DataGrid1.TabIndex = 10
    '
    'Form1
    '
    Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
    Me.ClientSize = New System.Drawing.Size(538, 281)
    Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.DataGrid1, Me.btnViewView, _
              Me.btnViewSP, Me.btnViewData, Me.btnDropTable, Me.btnCreateOthers, Me.btnAlterTable, _
              Me.CreateViewBtn, Me.CreateSPBtn, Me.CreateTableBtn, Me.CreateDBBtn})
    Me.Name = "Form1"
    Me.Text = "动态创建SQL Server数据库、表、存储过程等架构信息"
    CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).EndInit()
    Me.ResumeLayout(False)

  End Sub

#End Region

  ' 创建数据库
  Private Sub CreateDBBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles CreateDBBtn.Click
    conn = New SqlConnection(ConnectionString)
    ' 打开连接
    If conn.State <> ConnectionState.Open Then
      conn.Open()
    End If
    'MyDataBase为数据库名称
    Dim sql As String = "CREATE DATABASE MyDataBase ON PRIMARY (Name=MyDataBase_data, filename = " + _
        "'D:\MyDataBase.mdf', size=3," + "maxsize=5, filegrowth=10%) log on" + "(name=MyDataBase_log, " + _
        "filename='D:\MyDataBase.ldf',size=3," + "maxsize=20,filegrowth=1)"
    cmd = New SqlCommand(sql, conn)
    Try
      cmd.ExecuteNonQuery()
    Catch ae As SqlException
      MessageBox.Show(ae.Message.ToString())
    End Try
  End Sub
  '创建表
  Private Sub CreateTableBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles CreateTableBtn.Click
    conn = New SqlConnection(ConnectionString)
    ' 打开连接
    If conn.State = ConnectionState.Open Then
      conn.Close()
    End If
    ConnectionString = "Data Source=.;Initial Catalog=MyDataBase;User Id=sa;Password=;"
    conn.ConnectionString = ConnectionString
    conn.Open()
    sql = "CREATE TABLE myTable" + "(myId INTEGER CONSTRAINT PKeyMyId PRIMARY KEY," + _
      "myName CHAR(50) NOT Null, myAddress CHAR(255), myValues FLOAT)"
    cmd = New SqlCommand(sql, conn)
    Try
      cmd.ExecuteNonQuery()
      ' 添加纪录
      sql = "INSERT INTO myTable(myId, myName, myAddress, myValues) " + _
        "VALUES (1001, _'【孟宪会之精彩世界】之一', 'http://xml.sz.luohuedu.net/', 100 ) "
      cmd = New SqlCommand(sql, conn)
      cmd.ExecuteNonQuery()
      sql = "INSERT INTO myTable(myId, myName, myAddress, myValues) " + _
        "VALUES (1002, '【孟宪会之精彩世界】之二', 'http://www.erp800.com/net_lover/', 99) "
      cmd = New SqlCommand(sql, conn)
      cmd.ExecuteNonQuery()
      sql = "INSERT INTO myTable(myId, myName, myAddress, myValues) " + _
        "VALUES (1003, '【孟宪会之精彩世界】之三', 'http://xml.sz.luohuedu.net/', 99) "
      cmd = New SqlCommand(sql, conn)
      cmd.ExecuteNonQuery()
      sql = "INSERT INTO myTable(myId, myName, myAddress, myValues) " + _
        "VALUES (1004, '【孟宪会之精彩世界】之四', 'http://www.erp800.com/net_lover/', 100) "
      cmd = New SqlCommand(sql, conn)
      cmd.ExecuteNonQuery()
    Catch ae As SqlException
      MessageBox.Show(ae.Message.ToString())
    End Try

  End Sub
  '创建存储过程
  Private Sub CreateSPBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles CreateSPBtn.Click
    sql = "CREATE PROCEDURE myProc AS" + " SELECT myName, myAddress FROM myTable GO"
    ExecuteSQLStmt(sql)
  End Sub
  '创建视图
  Private Sub CreateViewBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles CreateViewBtn.Click
    sql = "CREATE VIEW myView AS SELECT myName FROM myTable"
    ExecuteSQLStmt(sql)

  End Sub
  '修改表
  Private Sub btnAlterTable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles btnAlterTable.Click
    sql = "ALTER TABLE MyTable ADD newCol datetime NOT NULL DEFAULT (getdate())"
    ExecuteSQLStmt(sql)
  End Sub
  '创建规则和索引
  Private Sub btnCreateOthers_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles btnCreateOthers.Click
    sql = "CREATE UNIQUE INDEX " + "myIdx ON myTable(myName)"
    ExecuteSQLStmt(sql)

    sql = "CREATE RULE myRule " + "AS @myValues >= 90 AND @myValues < 9999"
    ExecuteSQLStmt(sql)
  End Sub

  '删除表
  Private Sub btnDropTable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles btnDropTable.Click
    Dim sql As String = "DROP TABLE MyTable"
    ExecuteSQLStmt(sql)
  End Sub
  '浏览表数据
  Private Sub btnViewData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles btnViewData.Click
    conn = New SqlConnection(ConnectionString)
    If conn.State = ConnectionState.Open Then
      conn.Close()
    End If
    ConnectionString = "Data Source=.;Initial Catalog=MyDataBase;User Id=sa;Password=;"
    conn.ConnectionString = ConnectionString
    conn.Open()
    Dim da As New SqlDataAdapter("SELECT * FROM myTable", conn)
    Dim ds As New DataSet("myTable")
    da.Fill(ds, "myTable")
    DataGrid1.DataSource = ds.Tables("myTable").DefaultView
  End Sub
  '浏览存储过程
  Private Sub btnViewSP_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles btnViewSP.Click
    conn = New SqlConnection(ConnectionString)
    If conn.State = ConnectionState.Open Then
      conn.Close()
    End If
    ConnectionString = "Data Source=.;Initial Catalog=MyDataBase;User Id=sa;Password=;"
    conn.ConnectionString = ConnectionString
    conn.Open()
    Dim da As New SqlDataAdapter("myProc", conn)
    Dim ds As New DataSet("SP")
    da.Fill(ds, "SP")
    DataGrid1.DataSource = ds.DefaultViewManager
  End Sub
  '浏览视图
  Private Sub btnViewView_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles btnViewView.Click
    conn = New SqlConnection(ConnectionString)
    If conn.State = ConnectionState.Open Then
      conn.Close()
    End If
    ConnectionString = "Data Source=.;Initial Catalog=MyDataBase;User Id=sa;Password=;"
    conn.ConnectionString = ConnectionString
    conn.Open()
    Dim da As New SqlDataAdapter("SELECT * FROM myView", conn)
    Dim ds As New DataSet()
    da.Fill(ds)
    DataGrid1.DataSource = ds.DefaultViewManager
  End Sub

  Private Sub ExecuteSQLStmt(ByVal sql As String)
    conn = New SqlConnection(ConnectionString)
    ' 打开连接
    If conn.State = ConnectionState.Open Then
      conn.Close()
    End If
    ConnectionString = "Data Source=.;Initial Catalog=MyDataBase;User Id=sa;Password=;"
    conn.ConnectionString = ConnectionString
    conn.Open()
    cmd = New SqlCommand(sql, conn)
    Try
      cmd.ExecuteNonQuery()
    Catch ae As SqlException
      MessageBox.Show(ae.Message.ToString())
    End Try
  End Sub
End Class

时间: 2024-08-31 23:57:00

动态创建SQL Server数据库、表、存储过程的相关文章

Visual C#中动态操作SQL Server数据库

在编写数据库应用程序的时候,我们可以通过SQL语句来动态创建.修改数据库以及其中的对象.本文我就向大家介绍如何运用Visual C#来动态操作SQL Server数据库,其中包括如何创建一个SQL Server数据库以及如何创建其中的表.存储过程.视图.索引之类的数据库对象.本文还介绍了如何动态地修改表的模式,如何从表.存储过程以及视图中读取数据并显示在应用程序的数据库控件中. 我们知道SQL语句在操作数据库时运用得最多的是Select.Insert.Update和Delete等对于数据的操作,

SQL Server数据库的存储过程中定义的临时表,真的有必要显式删除(drop table #tableName)吗?

原文:SQL Server数据库的存储过程中定义的临时表,真的有必要显式删除(drop table #tableName)吗?   本文出处:http://www.cnblogs.com/wy123/p/6704619.html      问题背景 在写SQL Server存储过程中,如果存储过程中定义了临时表,有些人习惯在存储过程结束的时候一个一个显式地删除过程中定义的临时表(drop table #tName),有些人又没有这个习惯,对于不明真相的群众或者喜欢思考的人会问,存储过程中定义的临

python学习-python创建sql server 数据库问题求助

问题描述 python创建sql server 数据库问题求助 用python来创建一个数据库,如果存在就不用创建,如果不存在就创建一个: cursor.execute('if not exists(select * from master..sysdatabases where name = python) create database python;') 这样写编译不过,求助 解决方案 先用sql语句判断一下表格,不在,再调用创建

SQL SERVER数据库表记录只保留N天图文教程_MsSql

本文通过图文并茂的方式给大家展示SQL SERVER数据库表记录只保留N天图文教程,具体方法步骤请看下文: 第一步:首先设置SQL Server 代理服务为自动启动: "开始"-->"控制面板"-->"管理工具"-->"服务"-->右键" SQL SERVER 代理"-->"属性"-->"启动类型",选择 "自动启动 &q

SQL SERVER数据库表记录只保留N天图文教程

本文通过图文并茂的方式给大家展示SQL SERVER数据库表记录只保留N天图文教程,具体方法步骤请看下文: 第一步:首先设置SQL Server 代理服务为自动启动: "开始"-->"控制面板"-->"管理工具"-->"服务"-->右键" SQL SERVER 代理"-->"属性"-->"启动类型",选择 "自动启动 &q

ASP创建SQL Server数据库的两种方法

server|创建|数据|数据库 <% ************ 使用ADODB.Connect对象创建 ************************Dim oConnDim sDatabaseNamesDatabaseName = "CodeCreateDB"Set oConn = Server.CreateObject("ADODB.Connection")oConn.Open "Provider=SQLOLEDB;Data Source=(

SQL SERVER数据库表主键设计

1. 序言 当前,随着信息量的急剧增加,对于数据的存储和管理方式,各企业都逐渐摆脱了之前的依靠文件系统(文本文件或者Excel)或者一些桌面型的小型数据库系统(如Access.FoxBASE或者DBase)的状态,转而通过一些大型数据库来管理企业的信息.这些大型数据库系统包括Oracle.MS SQL Server或者IBM DB2.尽管目前数据库系统也在向面向对象的数据库系统方向发展,但是上述的传统的关系型数据库系统依然占据着主要位置. 笔者从九十年代末开始以关系型数据库系统为基础为客户进行管

c#编程实现word 文档如何导入SQL Server数据库表中

操作WORD配置说明 引入:Word的对象库文件"MSWORD.OLB"(word 2000为MSWORD9.OLB) 1.运行Dcomcnfg.exe 2.组件服务――计算机――我的电脑――DCOM配置――找到microsoft word 文档 3.点击属性 4.选择"安全性" 5.选定"使用自定义访问权限"和"使用自定义启动权限" 6.分别编辑权限,添加Everyone(ASPNET,VS Developers,Debug

Sql Server 数据库表查询结果导出为excel文件

相信大家常常会遇到将SqlServer查询结果导出到Excel的问题.如果导出的次数少,直接"Save Results As..."就是了; 1.1准备好查询语句 1.2选择数据库,启动导入和导出向导 1.3选择数据源 1.4选择目标 1.5 1.6 1.7 1.8 后续步骤不再附图,一直点"下一步"按钮就好. 2.但是当要分别在每个表取样,那就相当麻烦了.今天就为大家提供一个脱离office组件的可以将语句结果导出到Excel的过程,希望会对大家有帮助! ---导