如何在 C# 程序中执行存储过程

编程入门 行业动态 更新时间:2024-10-25 16:19:39
本文介绍了如何在 C# 程序中执行存储过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想从 C# 程序中执行这个存储过程.

I want to execute this stored procedure from a C# program.

我在 SqlServer 查询窗口中编写了以下存储过程并将其保存为存储1:

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

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(" Top 10 Most Expensive Products: "); 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(); } } }

这会显示异常Cannot find the stored procedure dbo.test.我需要提供路径吗?如果是,存储过程应该存储在哪个位置?

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# 程序中执行存储过程

本文发布于:2023-10-26 09:27:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529763.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:存储过程   程序   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!