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

时间:2021-03-13 19:15:41

一、创建存储过程

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