SqlServer存储过程(增删改查)

* IDENT_CURRENT 返回为任何会话和任何作用域中的特定表最后生成的标识值。

CREATE PROCEDURE [dbo].[PR_NewsAffiche_AddNewsEntity]
(
    @NewsTitle varchar(200),
    @NewsContent varchar(4000),
    @Creator varchar(50),
    @LastNewsId int output,
    @DepartId int
)
AS
BEGIN
    SET NOCOUNT ON;

    insert into tbNewsAffiche(Title,Content,Creator,CreateTime,Updator,UpdateTime,DepartId)
    values(@NewsTitle,@NewsContent,@Creator,getdate(),@Creator,getdate(),@DepartId)

    set @LastNewsId = IDENT_CURRENT(‘tbNewsAffiche‘)
END

存储过程方法体内定义及赋值:

declare @recordCount int
set @recordCount=0

SqlServer存储过程使用out传递出参数

====================================

增加:

存储过程

USE [testdb]
GO
/****** 对象:  StoredProcedure [dbo].[PR_QueueNewsAffiche_AddQueueNews]    脚本日期: 11/01/2013 15:40:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE proc [dbo].[PR_QueueNewsAffiche_AddQueueNews](@Content nvarchar(500),@NewsAfficheId int,@BeginTime datetime,@EndTime datetime,@Creator varchar(50),@CreateTime datetime,@Updator varchar(50),@UpdateTime datetime)
as
    insert into tbQueueNewsAffiche([Content],NewsAfficheId,BeginTime,EndTime,Creator,CreateTime,Updator,UpdateTime) values(@Content,@NewsAfficheId,@BeginTime,@EndTime,@Creator,getdate(),@Updator,getdate());

对应DAL层后台代码:

/// <summary>
        /// 添加
        /// </summary>
        /// <param name="newsInfo"></param>
        /// <returns></returns>
        public int Add(QueueNewsAffiche_NewsInfo newsInfo)
        {
            IDataParameter[] paramArray = new IDataParameter[]{
                Db.GetParameter("@Content",DbType.String,newsInfo.Content),
                Db.GetParameter("@NewsAfficheId",DbType.Int32,newsInfo.NewsAfficheId),
                Db.GetParameter("@BeginTime",DbType.DateTime,newsInfo.BeginTime),
                Db.GetParameter("@EndTime",DbType.DateTime,newsInfo.EndTime),
                Db.GetParameter("@Creator",DbType.String,newsInfo.Creator),
                Db.GetParameter("@CreateTime",DbType.DateTime,newsInfo.CreateTime),
                Db.GetParameter("@Updator",DbType.String,newsInfo.Updator),
                Db.GetParameter("@UpdateTime",DbType.DateTime,newsInfo.UpdateTime)
        };
            int returnValue = 0;
            try
            {
                returnValue = Db.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, "PR_QueueNewsAffiche_AddQueueNews", paramArray);
            }
            catch (System.Exception e)
            {
                LogHelper.Error("添加时出错" + e.ToString());
            }
            return returnValue;
        }

=======================================

删除:

存储过程

USE [testdb]
GO
/****** 对象:  StoredProcedure [dbo].[PR_QueueNewsAffiche_Delete]    脚本日期: 11/01/2013 15:46:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PR_QueueNewsAffiche_Delete](@Id int,@Result int output) //@Result为输出
AS
BEGIN
    IF EXISTS(SELECT 1 FROM tbQueueNewsAffiche //判断是否有数据SELECT top 1 FROM tbQueueNewsAffiche WHERE Id = @Id   不存在用not exists
            WHERE Id = @Id)
    BEGIN
        DELETE FROM tbQueueNewsAffiche
        WHERE Id = @Id
        set @Result=1;
    END
    else
    begin
    set @Result =0;
    end
END

对应DAL层代码:

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeleteById(int id)
        {
            IDataParameter[] paramArray = new IDataParameter[]{
                Db.GetParameter("@Result",DbType.Int32,ParameterDirection.Output),  //输出参数
                Db.GetParameter("@Id",DbType.Int32,id)
            };
            try
            {
                int effectedRows = Db.ExecuteSPNonQuery(ConnectionString, "PR_QueueNewsAffiche_Delete", paramArray);
                int result = Field.GetOutPutParam(paramArray[0], 0);
                return result;
            }
            catch (System.Exception ex)
            {
                Log.WriteUserLog("删除失败" + ex.ToString(), 0, 0, 0);
                return 0;
            }
        }

================================

修改:

存储过程:

USE [testdb]
GO
/****** 对象:  StoredProcedure [dbo].[PR_QueueNewsAffiche_Update]    脚本日期: 11/04/2013 10:54:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PR_QueueNewsAffiche_Update]
(
@Id int,
@Content nvarchar(500),
@BeginTime datetime,
@EndTime datetime,
@Updator varchar(50)
)
AS
BEGIN
    SET NOCOUNT ON;  这一句要注意:作用是不返回受影响的行数,一般做更新的不要设置,方便获取到返回的行数来判断是否更新成功。

    update tbQueueNewsAffiche
    set
        [Content][email protected],
        [email protected],
        [email protected],
        [email protected],
        UpdateTime=getdate()
    where [email protected]

END

对应DAL层代码:

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">排队新闻id</param>
        /// <param name="content"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="updator"></param>
        /// <returns></returns>
        public int Update(int id,string content,DateTime beginTime,DateTime endTime,string updator)
        {
            IDataParameter[] paramArray = new IDataParameter[] {
            Db.GetParameter("@Id",DbType.Int32,id),
            Db.GetParameter("@Content",DbType.String,content),
            Db.GetParameter("@BeginTime",DbType.DateTime,beginTime),
            Db.GetParameter("@EndTime",DbType.DateTime,endTime),
            Db.GetParameter("@Updator",DbType.String,updator)
            };

            int returnValue = 0;
            try
            {
                returnValue = Db.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, "PR_NewsAfficheQueue_Update", paramArray);
            }
            catch (System.Exception ex)
            {
                LogHelper.Error("更新时出错{PR_NewsAfficheQueue_Update}" + ex.ToString());
            }
            return returnValue;
        }

=================================

查询:

存储过程

USE [testdb]
GO
/****** 对象:  StoredProcedure [dbo].[PR_QueueNewsAffiche_GetAllNews]    脚本日期: 11/01/2013 15:53:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE proc [dbo].[PR_QueueNewsAffiche_GetAllNews](@NewsAfficheId int)
as
begin
    SET NOCOUNT ON;
    select
        Id,
        [Content],
        NewsAfficheId,
        BeginTime,
        EndTime,
        Creator,
        CreateTime,
        Updator,
        UpdateTime
    from dbo.tbQueueNewsAffiche where [email protected] order by BeginTime
end

对应DAL代码:

       /// <summary>
        /// 查询所有排队新闻
        /// </summary>
        /// <returns></returns>
        public List<QueueNewsAffiche_NewsInfo> GetList(int newsAfficheId)
        {
            IDataParameter[] paramArray = new IDataParameter[]{
                Db.GetParameter("@NewsAfficheId",DbType.Int32,newsAfficheId)
            };

            List<QueueNewsAffiche_NewsInfo> list = null;
            try
            {
                using (IDataReader reader = Db.ExecuteSPReader(ConnectionString, "PR_QueueNewsAffiche_GetAllNews", paramArray))
                {
                    list = new List<QueueNewsAffiche_NewsInfo>();
                    while (reader.Read())
                    {
                        QueueNewsAffiche_NewsInfo newsInfo = new QueueNewsAffiche_NewsInfo();
                        IDataRecord rec = reader as IDataRecord;

                        newsInfo.Id = Field.GetInt32(rec, "Id");
                        newsInfo.Content = Field.GetString(rec, "Content");
                        newsInfo.NewsAfficheId = Field.GetInt32(rec, "NewsAfficheId");
                        newsInfo.BeginTime = Field.GetDateTime(rec, "BeginTime");
                        newsInfo.EndTime = Field.GetDateTime(rec, "EndTime");
                        newsInfo.Creator = Field.GetString(rec, "Creator");
                        newsInfo.CreateTime = Field.GetDateTime(rec, "CreateTime");
                        newsInfo.Updator = Field.GetString(rec, "Updator");
                        newsInfo.UpdateTime = Field.GetDateTime(rec, "UpdateTime");
                        list.Add(newsInfo);
                    }
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.Error("查询时出错" + ex.ToString());
            }

            return list;
        }

根据id查询

USE [testdb]
GO
/****** 对象:  StoredProcedure [dbo].[PR_QueueNewsAffiche_GetNewsById]    脚本日期: 11/04/2013 13:44:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[PR_QueueNewsAffiche_GetNewsById]
(
    @Id int
)
AS
BEGIN
    SET NOCOUNT ON;

    select *
    from tbQueueNewsAffiche
    where [email protected]
END

对应DAL层代码:

        /// <summary>
        /// 根据id查询
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public QueueNewsAffiche_NewsInfo GetQueueNewsById(int id)
        {

            IDataParameter[] paramArray = new IDataParameter[] {
            Db.GetParameter("@Id",DbType.Int32,id)
            };
            QueueNewsAffiche_NewsInfo newsInfo = null;
            try
            {
                using (IDataReader reader = Db.ExecuteSPReader(ConnectionString, "PR_NewsAfficheQueue_GetNewsById", paramArray))
                {
                    while (reader.Read())
                    {
                        newsInfo = new QueueNewsAffiche_NewsInfo();
                        IDataRecord rec = reader as IDataRecord;

                        newsInfo.Content = Field.GetString(rec, "Content");
                        newsInfo.BeginTime = Field.GetDateTime(rec, "BeginTime");
                    }

                }
            }
            catch (System.Exception ex)
            {
                LogHelper.Error("查询排队新闻时出错{PR_NewsAfficheQueue_GetNewsById}" + ex.ToString());
            }
            return newsInfo;
        }

存储过程中执行SQL语句:

USE [BookSale]
GO
/****** 对象:  StoredProcedure [dbo].[SP_SaleBookCustomAddress_GetCustomAddressByUserIdList_1_19882]    脚本日期: 01/16/2014 15:30:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:
-- Create date:
-- Description:
-- =============================================
CREATE procedure [dbo].[SP_SaleBookCustomAddress_GetCustomAddressByUserIdList_1_19882]
(
    @UserIdList        nvarchar(max)
)
as
begin
exec(‘select * from SaleBookCustomAddress where UserId in (‘[email protected]+‘) and Status=1‘) 

end

DAL获取上面存储过程获得的内容:

/// <summary>
/// 根据多个UserId批量获取地址实体列表
/// </summary>
/// <param name="userIdList"></param>
/// <returns></returns>
public List<Entity.Activity.SaleBookCustomAddress> GetActivityRosterByUserIdList(string userIdList)
{
    IDataParameter[] par = new IDataParameter[] {
    AdoHelper.GetParameter("UserIdList",DbType.String ,userIdList )
    };

    List<SaleBookCustomAddress> rtn = new List<SaleBookCustomAddress>();
    try
    {
        using (IDataReader reader = AdoHelper.ExecuteReader(this.DefaultConnectionString, CommandType.StoredProcedure, "SP_SaleBookCustomAddress_GetCustomAddressByUserIdList_1_19882", par))
        {
            while (reader.Read())
            {
                SaleBookCustomAddress address = new SaleBookCustomAddress();
                address.UserId = Convert.ToInt64(reader["UserId"]);

                UserDataAccess userDB = new UserDataAccess();
                Users user = userDB.GetUserNickname(new int[] { Convert.ToInt32(address.UserId) })[0];
                if (user != null)
                {
                    address.NickName = user.UserName;
                }
                else
                {
                    address.NickName = "";
                }
                address.CustomName = Field.GetString(reader, "CustomName");
                address.Region = Field.GetString(reader, "Region");
                address.Province = Field.GetString(reader, "Province");
                address.City = Field.GetString(reader, "City");
                address.Street = Field.GetString(reader, "Street");
                address.Postcode = Field.GetString(reader, "Postcode");
                address.MobileNo = Field.GetString(reader, "MobileNo");
                address.FullTelNum = Field.GetString(reader, "TeleArea") + "-" + Field.GetString(reader, "Telephone") + "-" + Field.GetString(reader, "TeleExt");
                if (address.FullTelNum == "--")
                {
                    address.FullTelNum = "";
                }
                else
                {
                    if (string.IsNullOrEmpty(Field.GetString(reader, "TeleExt")))
                    {
                        address.FullTelNum = Field.GetString(reader, "TeleArea") + "-" + Field.GetString(reader, "Telephone");
                    }
                }
                address.LastUpdateTime = Field.GetDateTime(reader, "LastUpdateTime");

                rtn.Add(address);
            }
        }
    }
    catch (Exception ex)
    {
        Log.LogException(ex);
    }
    return rtn;
}

 零碎补充:

@AboutTheAuthor varchar(max),
@RMBOriginPrice    decimal(18,2), /*表示一共18位数字,其中包括2位小数点(整数部分则为16位)*/  decimal详解>>
@AuthorName   varchar(100)=‘‘, /*参数赋初值 */
@RecordCount   int=0 output /*赋初值的输出变量 */
select @RecordCount=count(1) from SaleBook where companyid=17

AS /*表示下面的为存储过程主体部分*/

/*@@表示全局变量(内置系统变量)、获取最新的主键id select @@rowcount受影响的行数 */
SELECT @@identity 

exec(@[email protected]+‘ ORDER BY CreateTime DESC‘) /*执行sql语句*/

WITH Mem_SALEBOOK_Book AS /*WITH的用法*/
(
  SELECT bookId
    FROM bookView V
    WHERE  CompanyId in ( select Item from dbo.fn_Split(@CompanyId,‘,‘) )
    and BookId= CASE @SearchType WHEN ‘bookid‘ THEN @SearchValue ELSE BookId END /*CASE...WHEN语法 */
    and BookName like CASE @SearchType WHEN ‘bookname‘ THEN @SearchValue ELSE BookName  END
)

SELECT M.*, SC.CompanyName as CompanyName FROM
    Mem_SALEBOOK_Book MM with (nolock)
inner join bookView M on MM.BookId=M.BookId
left join SaleCompany SC on M.CompanyId=SC.CompanyId

站内导航:

SqlServer存储过程实例讲解

站外扩展:

sqlserver函数大全

时间: 2024-12-04 13:11:45

SqlServer存储过程(增删改查)的相关文章

C# 对SqlServer数据库增删改查

http://www.worlduc.com/blog2012.aspx?bid=730767 用C#sqlserver实现增删改查 using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.Sql;using System.Data.SqlClient; namespace ConsoleApplication2{    class Program   

用C#sqlserver实现增删改查

using System.Data;using System.Data.SqlClient;//先打开两个类库文件SqlConnection con = new SqlConnection(); // con.ConnectionString = "server=505-03;database=ttt;user=sa;pwd=123";con.ConnectionString = "server=.;database=stu;uid=sa;pwd=sa";con.O

存储过程之六—存储过程增删改查

对于以下存储过程,表结构如下: -- ---------------------------- -- Table structure for person -- ---------------------------- DROP TABLE IF EXISTS `person`; CREATE TABLE `person` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) DEFAULT NULL, `age` int

C#学习笔记(3)——操作sqlserver数据库增删改查

说明(2017-5-25 16:29:35): 1. VS2010,视图->服务器资源管理器->数据连接->右键添加连接->服务器名(本机可以用点)->选择数据库->高级里面可以看其他选项,及连接字符串

C#中对sqlserver进行增删改查操作(简单易懂)

1.添加引用using System.Data;using System.Data.SqlData; 2.建立于数据库的连接,建议将它做成一个方法,方便多次利用.string sqlconnection = "data source = "注解1";database = 注解2;uid = "注解3";pwd ="注解4"";(其实还有很多种写法)可以参考http://www.cnblogs.com/delphinet/arc

关于MVC工厂模式的增删改查sql存储过程

这里MVC中用到了反射,工厂,泛型,接口 在搭建框架的时候,除了MVC的三层以外,还有泛型的接口层和工厂层 下面是dal层调用sql存储过程,增删改查,dal层继承了接口层,实现了接口层里面的方法 1 namespace DAL 2 { 3 public class DalHouse : IHouse 4 { 5 public int Add(HouseInfo m) 6 { 7 string sql = "pro_add"; 8 SqlParameter eid = new SqlP

设置Sql server用户对表、视图、存储过程、架构的增删改查权限

根据数据库Schema限制用户对数据库的操作行为 授予Shema dbo下对象的定义权限给某个用户(也就是说该用户可以修改架构dbo下所有表/视图/存储过程/函数的结构) use [Your DB NAME] GRANT VIEW DEFINITION ON SCHEMA :: dbo to [THE USER NAME] 回收某个用户对Shema dbo下对象的定义权限(也就是说该用户不可以修改架构dbo下所有表/视图/存储过程/函数的结构) use [Your DB NAME] DENY V

Dapper逆天入门~强类型,动态类型,多映射,多返回值,增删改查+存储过程案例演示

Dapper的牛逼就不扯蛋了,答应群友做个入门Demo的,现有园友需要,那么公开分享一下: 完整Demo:http://pan.baidu.com/s/1i3TcEzj 注 意 事 项:http://www.cnblogs.com/dunitian/p/5221058.html 平台之大势何人能挡? 带着你的Net飞奔吧! http://www.cnblogs.com/dunitian/p/4822808.html#skill 先安装一下Dapper(建议用nuget包来管理) 连接字符串: s

JavaWeb程序利用Servlet的对SQLserver增删改查操作

声明:学了几天终于将增删改查的操作掌握了,也发现了一些问题,所以总结一下. 重点:操作数据库主要用的是SQL语句跟其他无关. 一:前提知识:PreparedStatement PreperedStatement是Statement的子类,它的实例对象可以通过调用Connection.preparedStatement()方法获得,相对于Statement对象而言:PreperedStatement可以避免SQL注入的问题. Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出.P

VisualStudio2013内置SQLServer入门(二)--增删改查

前一篇 http://www.cnblogs.com/qixi233/p/4766451.html 这篇是sqlserver的操作 界面比较走心哈哈哈,将就着看,主要就是下面增删改查四个btn 对于sqlserver的操作基本就几个: 开关SqlConnection SqlCommand将"SQL命令"与"SQLConnection"连接 执行命令并根据返回值来将操作结果反馈给用户 现在开始操作:(代码比较简单,如果有书写不够规范之处请告知谢谢) 代码结构: 数据库