如何执行在C#程序中的存储过程 [英] How to execute a stored procedure within C# program
本文介绍了如何执行在C#程序中的存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从C#程序执行此存储过程。
我写了下面的存储过程中的一个SQLServer查询窗口并保存为
stored1:
使用主
走
创建的过程作为dbo.testDECLARE @command为varchar(1000),@i诠释
SET @i = 0
WHILE @i<五
开始
打印I值'+ CONVERT(VARCHAR(20),@ I)
EXEC(@command)
SET @i = @i + 1
结束
编辑:
使用系统;
使用System.Collections.Generic;
使用System.Text;
使用System.Data这;
使用System.Data.SqlClient的;
命名空间AutomationApp
{
类节目
{
公共无效RunStoredProc()
{
康涅狄格州的SqlConnection = NULL;
SqlDataReader的RDR = NULL; Console.WriteLine(\\ NTOP 10最贵的产品:\\ n); 尝试
{
康恩=新的SqlConnection(服务器=(当地);数据库=主;集成安全性= SSPI);
conn.Open();
CMD的SqlCommand =新的SqlCommand(dbo.test,康恩);
cmd.CommandType = CommandType.StoredProcedure;
RDR = cmd.ExecuteReader();
/ *而(rdr.Read())
{
Console.WriteLine(
产品:{0,} -25价格:$ {1,6:#### 00},
RDR [TenMostExpensiveProducts],
RDR [单价]);
} * /
}
最后
{
如果(参数conn!= NULL)
{
conn.Close();
}
如果(RDR!= NULL)
{
rdr.Close();
}
}
}
静态无效的主要(字串[] args)
{
Console.WriteLine(Hello World的);
程序P =新计划();
p.RunStoredProc();
Console.Read();
}
}
}
这显示异常找不到dbo.test
存储过程。我是否需要提供路径?如果是,在哪个位置应该在存储过程中存放?
解决方案
使用(VAR康恩=新的SqlConnection(的connectionString))
使用(VAR命令=新的SqlCommand(PROCEDURENAME,康涅狄格州){
的CommandType = CommandType.StoredProcedure}){
conn.Open();
command.ExecuteNonQuery();
}
I want to execute this stored procedure from a C# program.
I have written the following stored procedure in a SqlServer query window and saved it as stored1:
use master
go
create procedure dbo.test as
DECLARE @command as varchar(1000), @i int
SET @i = 0
WHILE @i < 5
BEGIN
Print 'I VALUE ' +CONVERT(varchar(20),@i)
EXEC(@command)
SET @i = @i + 1
END
EDITED:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace AutomationApp
{
class Program
{
public void RunStoredProc()
{
SqlConnection conn = null;
SqlDataReader rdr = null;
Console.WriteLine("\nTop 10 Most Expensive Products:\n");
try
{
conn = new SqlConnection("Server=(local);DataBase=master;Integrated Security=SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("dbo.test", conn);
cmd.CommandType = CommandType.StoredProcedure;
rdr = cmd.ExecuteReader();
/*while (rdr.Read())
{
Console.WriteLine(
"Product: {0,-25} Price: ${1,6:####.00}",
rdr["TenMostExpensiveProducts"],
rdr["UnitPrice"]);
}*/
}
finally
{
if (conn != null)
{
conn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World");
Program p= new Program();
p.RunStoredProc();
Console.Read();
}
}
}
This displays the exception Cannot find the stored procedure dbo.test
. Do I need to provide the path? If yes, in which location should the stored procedures be stored?
解决方案
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
command.ExecuteNonQuery();
}
这篇关于如何执行在C#程序中的存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文