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
====================================
增加:
存储过程
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]=@Content,
BeginTime=@BeginTime,
EndTime=@EndTime,
Updator=@Updator,
UpdateTime=getdate()
where Id=@Id 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 NewsAfficheId=@NewsAfficheId 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 Id=@Id
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 ('+@UserIdList+') 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(@sql+@where+' 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存储过程(增删改查)的更多相关文章
- NX二次开发-NX访问SqlServer数据库(增删改查)C#版
版本:NX9+VS2012+SqlServer2008r2 以前我写过一个NX访问MySQL数据库(增删改查)的文章https://www.cnblogs.com/nxopen2018/p/12297 ...
- 用C# sqlserver实现增删改查
using System.Data;using System.Data.SqlClient;//先打开两个类库文件SqlConnection con = new SqlConnection(); // ...
- SpringMVC+SpringJdbc+SQLServer+EasyUI增删改查
前言 前天用SpringJdbc连接了一把SQLServer,早上起来用SpringMVC+SpringJdbc+EasUI写了个增删改查的demo,主要是熟悉下SpringMVC相关知识点,如vie ...
- SQLServer数据库增删改查
一.数据库定义 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库.数据库的操作分为两种形式:一种是直接在数据库管理工具图形化界面进行操作:一种是使用数据库脚本进行操作,数据库脚本可 ...
- 连接SQLServer的增删改查方法代码
在Visual C++中用ADO进行数据库编程 1. 生成应用程序框架并初始化OLE/COM库环境 创建一个标准的MFC AppWizard(exe)应用程序CADOConnection,然后在使用A ...
- sqlserver的增删改查
select*from shuiguo 查询表 且小于等于7的范围) select distinct name from shuiguo--去除重复,只针对一列 select * from shui ...
- C#学习笔记(3)——操作sqlserver数据库增删改查
说明(2017-5-25 16:29:35): 1. VS2010,视图->服务器资源管理器->数据连接->右键添加连接->服务器名(本机可以用点)->选择数据库-> ...
- C#中对sqlserver进行增删改查操作(简单易懂)
1.添加引用using System.Data;using System.Data.SqlData; 2.建立于数据库的连接,建议将它做成一个方法,方便多次利用.string sqlconnectio ...
- 关于MVC工厂模式的增删改查sql存储过程
这里MVC中用到了反射,工厂,泛型,接口 在搭建框架的时候,除了MVC的三层以外,还有泛型的接口层和工厂层 下面是dal层调用sql存储过程,增删改查,dal层继承了接口层,实现了接口层里面的方法 1 ...
- 设置Sql server用户对表、视图、存储过程、架构的增删改查权限
根据数据库Schema限制用户对数据库的操作行为 授予Shema dbo下对象的定义权限给某个用户(也就是说该用户可以修改架构dbo下所有表/视图/存储过程/函数的结构) use [Your DB N ...
随机推荐
- path变量修改后无法保存
Eclipse启动时出现错误: A Java Runtime Environment (JRE) or Java Development Kit(JDK) must be available in o ...
- line search中的重要定理 - 梯度与方向的点积为零
转载请注明出处:http://www.codelast.com/ 对精确的line search(线搜索),有一个重要的定理: ∇f(xk+αkdk)Tdk=0 这个定理表明,当前点在dk方向上移动到 ...
- C++ 数据结构概念
C++ 数据结构概念 数据结构起源 计算机从解决数值计算问题到解决生活中的问题 现实生活中的问题涉及不同个体间的复杂联系 需要在计算机程序中描述生活中个体间的联系 数据结构主要研究非数值计算程序问题中 ...
- PHP 字符串数组按照拼音排序的问题
拼音排序的规则: 字符串包括特殊字符.数字.英文字符.中文字符等等,排序结果要求,特殊字符排在第一梯队,将其按照首个字符ascii码表进行排序,数字字符排在第二梯队,将首个字符数字按照数字大小排序,英 ...
- 【转】__ATTRIBUTE__ 你知多少
__ATTRIBUTE__ 你知多少? GNU C 的一大特色就是__attribute__ 机制.__attribute__ 可以设置函数属性(Function Attribute ).变量属性(V ...
- Missing $ inserted解决方法
目录 问题描述 解决 参考 问题描述 在学习LaTex Tutorial的时候,按照教程输入矩阵的时候发现出现了 ! Missing $ inserted的错误. 解决 在矩阵前后要加上$,如图所示 ...
- 安装GourdScanV2的踩坑过程
环境:ubuntu 16.04.1 1.安装dcoker sudo apt-get install docker.io 坑:sudo apt-get install docker 2.下载关于dock ...
- 【XSY2307】树的难题
Description Solution 看到这种路径统计问题,一般就想到要用点分治去做. 对于每个重心\(u\),统计经过\(u\)的合法的路径之中的最大值. 第一类路径是从\(u\)出发的,直接逐 ...
- 20135239 益西拉姆 linux内核分析 进程的切换和系统的一般执行过程
week 8 进程的切换和系统的一般执行过程 [ 20135239 原文请转载请注明出处 <Linux内核分析>MOOC课程http://mooc.study.163.com/course ...
- 编译安装haproxy开启支持SSL
1.下载程序包 # wget http://www.haproxy.org/download/1.7/src/haproxy-1.7.5.tar.gz # tar xvf haproxy-1.7.5. ...