存储过程生成器






3.11/5 (12投票s)
2005年8月8日
2分钟阅读

38847

769
SQL Server 存储过程生成器。
引言
该项目用于生成指定表中插入、更新和删除的存储过程。
描述
在编写查询时,我们最常需要做的工作是编写用于操作数据库中现有表数据的基本存储过程。这可能是导致语法错误最多的步骤。本文中的应用程序有助于避免此类错误。你只需要填写所需的字段,你的存储过程就准备好了。当然,生成的查询可以通过一些修改进一步用于你的代码或服务器。
如何使用
- 将项目下载到你的计算机。
- 编译/运行它。
- 输入表名和列数。
- 按下“重新加载”按钮。
- 填写主键、列名、数据类型、大小和允许空值的字段。
- 在按下“生成查询”按钮之前,请检查:是否至少有一列具有主键,并且所有列都不是主键。这对于生成更新和删除查询非常重要。
- 按下“生成查询”按钮。
示例
图 1. 运行项目后出现的窗口。
填写表名和列数文本框后,点击“重新加载”按钮
图 2. 生成表列的字段。
接下来,在填写列表数据并点击“生成查询”按钮后
图 3. 创建查询。
现在你可以通过点击每个文本框下方的“复制到剪贴板”按钮,将它们复制并在你的应用程序中使用。
代码注释
让我们首先查看点击“重新加载”按钮后执行的代码。
try
{
for(int i = 0; i<no; i++) colList[i].Dispose();
no = Convert.ToInt32(txtColumnNo.Text);
colList = new ucColumn[no];
for(int i = 0; i<no; i++)
{
colList[i] = new ucColumn();
colList[i].Location = new System.Drawing.Point(8, 90+i*28);
colList[i].Size = new System.Drawing.Size(432, 21);
this.Controls.Add(colList[i]);
}
}
catch(Exception ex)
{
MessageBox.Show("Please type valid integer for number of columns.",
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
首先,输入的“列数”被转换为整数,用于动态声明和创建控件数组。控件距离步长值经过仔细选择 - 90+i*28 - 对应于其尺寸。
用于查询生成的代码如下,例如,对于插入查询
if(checkvalidity()=="")
{
if((no > 0) && (txtTableName.Text != ""))
{
以上代码检查列类型的大小、列数和表名是否正确提供。
txtInsertQuery.Text =
"CREATE PROCEDURE dbo.sp_Insert_" + txtTableName.Text;
txtInsertQuery.Text += "\r\n(";
if(no>1)
{
for(int i=0;i<no-1;i++)
txtInsertQuery.Text += "\r\n @"+colList[i].txtColumn.Text +
" "+colList[i].cmbType.Text+
createtype(colList[i].txtSize.Text)+
allownull(colList[i].cmbNull.Text)+",";
txtInsertQuery.Text += "\r\n @"+colList[no-1].txtColumn.Text +
" "+colList[no-1].cmbType.Text +
createtype(colList[no-1].txtSize.Text)+
allownull(colList[no-1].cmbNull.Text);
}
else
{
txtInsertQuery.Text += "\r\n @"+colList[0].txtColumn.Text+
" "+colList[0].cmbType.Text+
createtype(colList[0].txtSize.Text)+
allownull(colList[0].cmbNull.Text);
}
txtInsertQuery.Text += "\r\n)";
然后是创建过程头和变量声明。
txtInsertQuery.Text +=
"\r\nAS\r\nINSERT INTO "+txtTableName.Text+"(";
if(no>1)
{
for(int i=0;i<no-1;i++)
txtInsertQuery.Text += colList[i].txtColumn.Text+", ";
txtInsertQuery.Text += colList[no-1].txtColumn.Text+")";
}
else
{
txtInsertQuery.Text += colList[0].txtColumn.Text+")";
}
txtInsertQuery.Text += "\r\nVALUES(";
if(no>1)
{
for(int i=0;i<no-1;i++)
txtInsertQuery.Text += "@"+colList[i].txtColumn.Text+", ";
txtInsertQuery.Text += "@"+colList[no-1].txtColumn.Text+")";
}
else
{
txtInsertQuery.Text += "@"+colList[0].txtColumn.Text+")";
}
txtInsertQuery.Text += "\r\nGO";
因此创建了插入查询。
更新和删除的代码类似,但有一些额外的要求。
祝你查询愉快!