程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#調用SQL Server參數過程傳參

C#調用SQL Server參數過程傳參

編輯:C#入門知識

C#調用SQL Server參數過程傳參


-SQL SERVER生成測試環境:

 

Create database Test; 
go
USE [Test]
GO
if OBJECT_ID('Tab2','U') is not null
	drop table Tab2
go
CREATE TABLE [dbo].[Tab2](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TabID] [int] NOT NULL,
	[Name2] [nvarchar](50) NULL
) 
GO
SET IDENTITY_INSERT [dbo].[Tab2] ON 
GO
INSERT [dbo].[Tab2] ([ID], [TabID], [Name2]) VALUES (1, 245575913, N'ID')
GO
INSERT [dbo].[Tab2] ([ID], [TabID], [Name2]) VALUES (2, 245575913, N'name')
GO
INSERT [dbo].[Tab2] ([ID], [TabID], [Name2]) VALUES (3, 277576027, N'ID')
GO
INSERT [dbo].[Tab2] ([ID], [TabID], [Name2]) VALUES (4, 277576027, N'Name2')
GO
INSERT [dbo].[Tab2] ([ID], [TabID], [Name2]) VALUES (5, 277576027, N'TabID')
GO
SET IDENTITY_INSERT [dbo].[Tab2] OFF
GO
if OBJECT_ID('P2','P') is not null
	drop procedure P2
go
Create procedure P2
(
@StartID int,
@EndID int,
@Rowcount int output
)
as
select * from Tab2 where ID between @StartID and @EndID
set @Rowcount=@@ROWCOUNT
go
--打開Visual Studio—創建項目—選擇【控制台應用程序】

 

 

#region Using Directives
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#endregion

namespace TestExecute
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection thisConnection = new SqlConnection(@Server=(Local);Database=Test;User ID=sa;Password=1);
            thisConnection.Open();
            SqlCommand thisCommand = thisConnection.CreateCommand();
            thisCommand.CommandType = CommandType.StoredProcedure;
            thisCommand.CommandText = P2;
            IDataParameter[] parameters = {
                new SqlParameter(@StartID,SqlDbType.Int),
                new SqlParameter(@EndID,SqlDbType.Int),
                new SqlParameter(@Rowcount,SqlDbType.Int),
                new SqlParameter(return_value,SqlDbType.Int)
            };
            parameters[0].Value = 1;
            parameters[1].Value = 5;
            parameters[2].Direction = ParameterDirection.Output;
            parameters[3].Direction = ParameterDirection.ReturnValue;
            thisCommand.Parameters.AddRange(parameters);
            thisCommand.ExecuteNonQuery();
            thisConnection.Close();
            Console.WriteLine(@Rowcount:{0}
Return_value:{1},parameters[2].Value,parameters[3].Value);
            Console.ReadKey();
        }
    }
}

 

--按F5運行結果:

/

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved