SQL server2014数据库存储过程 实现游标循环读取 循环插入数据

yuanshuai 2020-03-06

USE [Text]
GO
/****** Object:  StoredProcedure [dbo].[TT]    Script Date: 2020/3/6 11:37:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[TT]
@IID INT

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @ID INT ,@NAME varchar(50)
DECLARE My_Cursor CURSOR --定义游标
FOR (SELECT * FROM Table2 WHERE ID=@IID) --查出需要的集合放到游标中
OPEN My_Cursor; --打开游标
FETCH NEXT FROM My_Cursor INTO @ID,@NAME; --读取第一行数据(将MemberAccount表中的UserId放到@UserId变量中)
WHILE @@FETCH_STATUS = 0
    BEGIN
      PRINT @NAME; --打印数据(打印MemberAccount表中的UserId)
        INSERT INTO Table3 VALUES(@NAME)
       FETCH NEXT FROM My_Cursor INTO @ID,@NAME; 
    END

CLOSE My_Cursor; --关闭游标
DEALLOCATE My_Cursor; --释放游标
END

c# 调用代码:

// 数据库连接字符串
            string connStr = "数据库连接字符串“;
            // 创建Connection 对象
            SqlConnection conn = new SqlConnection(connStr);
            // 打开数据库连接
            conn.Open();
            SqlCommand cmd = new SqlCommand("TT", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@IID", SqlDbType.Int) { Value = 1 });
            //如cmd.Parameters.Add(new SqlParameter("@riqi", SqlDbType.DateTime, 8));
            //把具体的值传给输入参数
            cmd.Parameters["@IID"].Value = 2;
            //如cmd.Parameters["@riqi"].Value = this.textBox1.Text;
            //执行存储过程
            cmd.ExecuteNonQuery();

相关推荐

李高峰 / 0评论 2020-05-25