一、创建存储过程

if Exists(select name from sysobjects where NAME = 'sp1LoginUser' and type='P')
drop procedure sp1LoginUser
GO
CREATE PROCEDURE [dbo].[sp1LoginUser]
-- Add the parameters for the stored procedure here
@username NVARCHAR(50)
AS
BEGIN
DECLARE @identityCount INT
SELECT * FROM dbo.LoginUser where IsDelete=0
AND UserName=@username
SELECT TOP 1 @identityCount= ID FROM dbo.LoginUser ORDER BY ID DESC
select @identityCount
END
GO

二、执行存储过程

EXEC sp1LoginUser 'admin'

三、创建函数

1、
ALTER FUNCTION [dbo].[fn1GetRoleNane](
@userid INT
)
returns varchar(500)
AS
begin
DECLARE @tmp VARCHAR(500)
SELECT @tmp=isnull(@tmp+',','')+ltrim(r.roleName) FROM UserAndRole ar, Role r WHERE r.RoleID=ar.roleID AND ar.userid=@userid
RETURN ISNULL(@tmp,'')
END

2、

select * from Split(@strwhere , ','))
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
CREATE FUNCTION [dbo].[Split]
(
@c VARCHAR(MAX) ,
@split VARCHAR(50)
)

RETURNS @t TABLE ( col VARCHAR(50) )
AS
BEGIN
WHILE ( CHARINDEX(@split, @c) <> 0 )
BEGIN
INSERT @t( col )
VALUES ( SUBSTRING(@c, 1, CHARINDEX(@split, @c) - 1) )
SET @c = STUFF(@c, 1, CHARINDEX(@split, @c), '')
END
INSERT @t( col ) VALUES ( @c )
RETURN
END
GO

四、 sqlserver 日期字段类型转字符串
(Select Convert(Varchar(10),FeeTime,120) Username, 把日期类型字段转为指定长度的字符串

五、创建分页存储过程
Create PROCEDURE usp_PagingLarge
@TableNames VARCHAR(200),--表名,可以是多个表,但不能用别名
@PrimaryKey VARCHAR(100),--主键,可以为空,但@Order为空时该值不能为空
@Fields VARCHAR(200),--要取出的字段,可以是多个表的字段,可以为空,为空表示select*
@PageSize INT,--每页记录数
@CurrentPage INT,--当前页,表示第页
@Filter VARCHAR(200)='',--条件,可以为空,不用填where
@Group VARCHAR(200)='',--分组依据,可以为空,不用填groupby
@Order VARCHAR(200)=''--排序,可以为空,为空默认按主键升序排列,不用填orderby
AS
BEGIN
DECLARE @SortColumn VARCHAR(200)
DECLARE @Operator CHAR(2)
DECLARE @SortTable VARCHAR(200)
DECLARE @SortName VARCHAR(200)
IF @Fields=''
SET @Fields='*'
IF @Filter=''
SET @Filter='Where1=1'
ELSE
SET @Filter='Where'+@Filter
IF @Group<>''
SET @Group='GROUPBY'+@Group

IF @Order<>''
BEGIN
DECLARE @pos1 INT,@pos2 INT
SET @Order=REPLACE(REPLACE(@Order,'asc','ASC'),'desc','DESC')
IF CHARINDEX('DESC',@Order)>0
IF CHARINDEX('ASC',@Order)>0
BEGIN
IF CHARINDEX('DESC',@Order)<CHARINDEX('ASC',@Order)
SET @Operator='<='
ELSE
SET @Operator='>='
END
ELSE
SET @Operator='<='
ELSE
SET @Operator='>='
SET @SortColumn=REPLACE(REPLACE(REPLACE(@Order,'ASC',''),'DESC',''),'','')
SET @pos1=CHARINDEX(',',@SortColumn)
IF @pos1>0
SET @SortColumn=SUBSTRING(@SortColumn,1,@pos1-1)
SET @pos2=CHARINDEX('.',@SortColumn)
IF @pos2>0
BEGIN
SET @SortTable=SUBSTRING(@SortColumn,1,@pos2-1)
IF @pos1>0
SET @SortName=SUBSTRING(@SortColumn,@pos2+1,@pos1-@pos2-1)
ELSE
SET @SortName=SUBSTRING(@SortColumn,@pos2+1,LEN(@SortColumn)-@pos2)
END
ELSE
BEGIN
SET @SortTable=@TableNames
SET @SortName=@SortColumn
END
END
ELSE
BEGIN
SET @SortColumn=@PrimaryKey
SET @SortTable=@TableNames
SET @SortName=@SortColumn
SET @Order=@SortColumn
SET @Operator='>='
END

DECLARE @type varchar(50)
DECLARE @prec int
Select @type=t.name,@prec=c.prec
FROM sysobjects o
JOIN syscolumns c on o.id=c.id
JOIN systypes t on c.xusertype=t.xusertype
Where o.name=@SortTable AND c.name=@SortName
IF CHARINDEX('char',@type)>0
SET @type=@type+'('+CAST(@prec AS varchar)+')'

DECLARE @TopRows INT
SET @TopRows=@PageSize*@CurrentPage+1
print @TopRows
print @Operator
EXEC('
DECLARE @SortColumnBegin'+@type+'
SET ROWCOUNT'+@TopRows+'
Select @SortColumnBegin='+@SortColumn+'FROM'+@TableNames+''+@Filter+''+@Group+'or DERBY'+@Order+'
SET ROWCOUNT'+@PageSize+'
Select'+@Fields+'FROM'+@TableNames+''+@Filter+'AND'+@SortColumn+''+@Operator+'@SortColumnBegin'+@Group+'or DERBY'+@Order+'
')
END

GO

int.TryParse(areaID.ToString(), out areaID);
六、--case when的用法
select (case cardstatus
when 0 then '卡发行'
when 1 then '卡延期'
when 2 then '挂失'
when 3 then '解挂'
when 4 then '补发'
when 5 then '退款'
when 6 then '销户'
else '其它'
end ) as '卡片类型',count(*) as '数量'
from CCardOperation
group by cardstatus

--sum case when 用法
select
sum(case cardstatus when 0 then 1 else 0 end) as '卡发行' ,
sum(case cardstatus when 1 then 1 else 0 end ) as '卡延期',
sum(case cardstatus when 2 then 1 else 0 end) as '挂失',
sum(case cardstatus when 3 then 1 else 0 end) as '解挂',
sum(case cardstatus when 4 then 1 else 0 end) as '补发',
sum(case cardstatus when 5 then 1 else 0 end) as '退款',
sum(case cardstatus when 6 then 1 else 0 end) as '销户'
from CCardOperation

七、拼接字段

select(select count(1) from CCardOperation where cardstatus=0) as '卡发行',
(select count(1) from CCardOperation where cardstatus=1) as '卡延期',
(select count(1) from CCardOperation where cardstatus=2) as '卡挂失'

八、创建一个游标

update [Vw_Sale_PersonCard] a set a.deptid=b.deptid where exists
(
(select b.deptid from [Sale_SaleRecord] b on a.yktid=b.yktid )

游标
Declare MyCusror Cursor Scroll

For select id, yktid from [Sale_SaleRecord];

Open MyCusror
declare @GoodsCode int

declare @GoodsName int
Fetch next From MyCusror
Into @GoodsCode,@GoodsName

While(@@Fetch_Status = 0)
Begin

Begin
update [Sale_SaleRecord] set deptid=(select deptid from [Vw_Sale_PersonCard] as a where a.yktid=@GoodsName) where id=@GoodsCode
End

Fetch next From MyCusror
Into @GoodsCode,@GoodsName

End
Close MyCusror
Deallocate MyCusror

九、创建视图及按月查询

IF EXISTS(SELECT * FROM sysobjects WHERE id=OBJECT_ID('v_ShouldPaymentRecordsByMonth'))
DROP VIEW v_ShouldPaymentRecordsByMonth
go
CREATE VIEW v_ShouldPaymentRecordsByMonth
AS
SELECT a.CustomerName,CONVERT(NVARCHAR(7),a.PaymentDate,120) AS Yue ,SUM(CASE ad.IsDiscount WHEN '0' THEN ad.ShouldPayment ELSE -ad.ShouldPayment END) Amount
FROM dbo.Account a
LEFT JOIN dbo.AccountDetail ad ON a.AccountNo=ad.AccountNo
GROUP BY a.CustomerName,CONVERT(NVARCHAR(7),a.PaymentDate,120)

SELECT a.AccountNo,a.CustomerName,CONVERT(NVARCHAR(7),a.PaymentDate,120) ,p.Name,
SUM(CASE ad.IsDiscount WHEN '0' THEN ad.ShouldPayment ELSE -ad.ShouldPayment END) Amount
FROM dbo.Account a
LEFT JOIN dbo.AccountDetail ad ON a.AccountNo=ad.AccountNo
LEFT JOIN dbo.PaymentItem p ON p.PaymentItem=ad.PaymentItem
Group BY a.AccountNo,a.CustomerName,CONVERT(NVARCHAR(7),a.PaymentDate,120) ,p.Name

十、存储过程动态行转列

-------------存储过程动态行转列 -------------
IF EXISTS(SELECT * FROM sysobjects WHERE id=OBJECT_ID('pro_ShouldPaymentRecordsDetail'))
DROP procedure pro_ShouldPaymentRecordsDetail
go
CREATE procedure pro_ShouldPaymentRecordsDetail
(
@tableName SYSNAME ,--行转列表
@groupColumn SYSNAME, --分组字段
--@otherDiplayColumn NVARCHAR(max), --输出其它列字段
@row2column SYSNAME, --行变列的字段
@row2columnValue SYSNAME, --行变列值的字段
@sql_where NVARCHAR(100)--WHERE UserName = ''王五''
)
AS
BEGIN
DECLARE @sql_str NVARCHAR(MAX)
DECLARE @sql_col NVARCHAR(MAX)
DECLARE @otherDiplayColumnName NVARCHAR(MAX)

--从行数据中获取可能存在的列
SET @sql_str = N'
SELECT @sql_col_out = ISNULL(@sql_col_out + '','','''') + QUOTENAME(['+@row2column+'])
FROM ['+@tableName+']'+@sql_where+' GROUP BY ['+@row2column+']'
PRINT @sql_str
EXEC sp_executesql @sql_str,N'@sql_col_out NVARCHAR(MAX) OUTPUT',@sql_col_out=@sql_col OUTPUT
PRINT @sql_col

SET @sql_str = N'
SELECT * FROM (
SELECT ['+@groupColumn+'],['+@row2column+'],['+@row2columnValue+'] FROM ['+@tableName+']'+@sql_where+') p PIVOT
(SUM(['+@row2columnValue+']) FOR ['+@row2column+'] IN ( '+ @sql_col +') ) AS pvt
ORDER BY pvt.['+@groupColumn+']'
PRINT @sql_str
exec (@sql_str)
END
go

----执行存储过程
EXEC pro_ShouldPaymentRecordsDetail 'v_ShouldPaymentRecordsDetail','AccountNo','Name','Amount',' where AccountNo=''888868-2015091815341812'' '

十一、视图

---------- 查询客户该账单总账----------
IF EXISTS(SELECT * FROM sysobjects WHERE id=OBJECT_ID('v_ShouldPaymentRecords'))
DROP VIEW v_ShouldPaymentRecords
go
CREATE VIEW v_ShouldPaymentRecords
AS
SELECT a.AccountNo, a.CustomerName,a.PaymentDate ,SUM(CASE ad.IsDiscount WHEN '0' THEN ad.ShouldPayment ELSE -ad.ShouldPayment END) Amount
FROM dbo.Account a
LEFT JOIN dbo.AccountDetail ad ON a.AccountNo=ad.AccountNo
GROUP BY a.AccountNo, a.CustomerName,a.PaymentDate

go
-------------查询账单明细------------------------------
IF EXISTS(SELECT * FROM sysobjects WHERE id=OBJECT_ID('v_ShouldPaymentRecordsDetail'))
DROP VIEW v_ShouldPaymentRecordsDetail
go
CREATE VIEW v_ShouldPaymentRecordsDetail
AS
SELECT a.AccountNo,a.CustomerName,a.PaymentDate ,p.Name,
SUM(CASE ad.IsDiscount WHEN '0' THEN ad.ShouldPayment ELSE -ad.ShouldPayment END) Amount
FROM dbo.Account a
LEFT JOIN dbo.AccountDetail ad ON a.AccountNo=ad.AccountNo
LEFT JOIN dbo.PaymentItem p ON p.PaymentItem=ad.PaymentItem
Group BY a.AccountNo,a.CustomerName,a.PaymentDate ,p.Name

中等难度SQL语句(存储过程,分页,拼接字段、游标,日期类型转换,动态行转列,视图)汇总的更多相关文章

  1. 使用传入的总记录数实现一条sql语句完成分页查询

    使用传入的总记录数实现一条sql语句完成分页查询     问题:在传统的分页查询的实现中不可避免的需要两条sql语句,一条用于查询数据一条用于查询总记录数.如下面的实际代码所示: Img1 当然如果使 ...

  2. (转载)sql语句解决分页问题

    <来源网址:http://www.delphifans.com/infoview/Article_353.html>sql语句解决分页问题日期:2005年1月17日 作者:treemon2 ...

  3. Sql Service存储过程分页

    一起是用oracle数据库..感觉oracle数据库强大.查询速度是杠杠的.换了家公司用的是SQL SERVICE.以前用了1年现在捡回以前的记忆.动手写了动态SQL过存储过程分页.感觉和oracle ...

  4. SQL语句添加删除修改字段及一些表与字段的基本操作

    用SQL语句添加删除修改字段 1.增加字段     alter table docdsp    add dspcode char(200)2.删除字段     ALTER TABLE table_NA ...

  5. Sql语句varchar或nvarchar字段条件前加N的性能差异

    Sql语句varchar或nvarchar字段条件前加N的话是对这个字段进行Unicode编码, 这样做的目的是避免在这种字段中存入俄文.韩文.日文的情况下有可能会出现乱码. 但这样做也会有性能问题, ...

  6. 用SQL语句添加删除修改字段、一些表与字段的基本操作、数据库备份等

    用SQL语句添加删除修改字段 1.增加字段 alter table docdsp add dspcode char(200) 2.删除字段 ALTER TABLE table_NAME DROP CO ...

  7. SQL语句添加删除修改字段[sql server 2000/2005]

    用SQL语句添加删除修改字段1.增加字段     alter table docdsp    add dspcodechar(200)2.删除字段     ALTER TABLE table_NAME ...

  8. SQL语句添加删除修改字段

    用SQL语句添加删除修改字段1.增加字段     alter table docdsp    add dspcodechar(200)2.删除字段     ALTER TABLE table_NAME ...

  9. SQL语句获取数据库中的表主键,自增列,所有列

    SQL语句获取数据库中的表主键,自增列,所有列   获取表主键 1:SELECT TABLE_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_U ...

随机推荐

  1. 【AngularJS】—— 5 表单

    这部分,我们写一个表单程序,使用angularjs的检测并完成表单属性的获取与拷贝. 在AngularJS中,也支持html5中多种控件的自动检测,如:text.number.url.email.ra ...

  2. iOS分类、延展和子类的区别

    iOS分类.延展和子类的区别 类别.延展.子类的区别   类别 延展 子类 功能 为类添加方法,不用知道类的源码,添加变量(通过运行时,具体参考下面注解) 为类添加私有变量和私有方法,在类的源文件中书 ...

  3. 微信公众平台开放JS-SDK(微信内网页开发工具包)

    微信公众平台开放JS-SDK(微信内网页开发工具包),这次开放接口是质的飞跃,是对开发者和广大用户一个利好的消息.未来的公众号图文消息会更丰富多彩,准备脑洞大开吧!(第三方平台正式支持接入微信公众平台 ...

  4. java系列-安装MySql(三)

    第一大步:MySQL安装文件分为两种,一种是msi格式的,一种是zip格式的.如果是msi格式的可以直接点击安装,按照它给出的安装提示进行安装(相信大家的英文可以看懂英文提示),一般MySQL将会安装 ...

  5. bootstrap实现弹出窗口

    bootstrap使用modal-dialog实现弹对话框. 一个对话框包含3部分: 对话框头部 modal-header 对话框内容体 modal-body 对话框底部 modal-footer 如 ...

  6. MVC后台传dt数据

    //MVC后台传dt数据 public JsonResult TeacherVoteInfo([FromBody]Teacher_VoteModel model) { string tname = m ...

  7. Linux下查看nginx安装目录

    输入命令行: ps  -ef | grep nginx master process后边的目录即是.

  8. 利用Jquery的load函数实现页面的动态加载

    利用Jquery的load函数实现页面的动态加载  js的强大功能相信大家都知晓,今天通过jquery的库函数load可以更加方便的实现页面的动态刷新,经过几天的研究与探索,终于有所成效!吾心甚蔚! ...

  9. NoSuchMethodException问题总结

    1.编译异常,这个很容易发现并解决: method真的没有 替换jar包没有clean project. 2.编译正常,运行报错 这是一个遇到之后让人纳闷的异常,脑袋不转弯的时候真的容易被卡住.这时只 ...

  10. 理解js中this的指向

         学习自原文  http://www.cnblogs.com/pssp/p/5216085.html后的一点小结(原文作者总结的很棒^_^)! 关于js中this的指向,在函数定义的时候还无法 ...