/****** 对象:  StoredProcedure [dbo].[AddOrder_Proc]    脚本日期: 04/09/2012 18:25:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*                                
function:添加新的订单                                
careatetime:201008                                
author:                                
modify history:                                
-------------------
*/
CREATE PROCEDURE [dbo].[AddOrder_Proc]
@orderID int out,                                    
@memberID int, --会员ID                                    
@cartID nvarchar(50),  --购物车ID   

@rName nvarchar(20),--收货人姓名
@rEmail nvarchar(20),--收货人EMAIL
@rPhone nvarchar(20),--收货人联系电话
@rPostalcode nvarchar(20),--收货人邮编
@rAddress  nvarchar(100),--收货人详细地址
@topAreaID int,--省级ID
@subAreaID int,--市级ID
@thirdAreaID int,--县区级ID


@isSaveAddress int,--是否保存收货人地址到地址簿    
@shipAddressID int,--地址簿ID,

@payType int,--支付类型
@shippingID int,--配送方式
@shippingTime nvarchar(50), --送货时间
@status int,--订单状态
@code nvarchar(20),--代销人的代销号

@needInvoice tinyint,  --是否需要发票    
--@invoiceType int,--发票类型
@taxRate decimal(18,2),--税金比例
   
 
@useAdvPay tinyint,--是否使用预付款
@advancePayment decimal(18,2),--使用的预付款金额

@useScore tinyint,--是否使用积分
@usedScore int,--使用的积分
@scoreAmount decimal(18,2),--使用积分抵消的金额

@remark nvarchar(300),  --Remark 备注                                    
@orderType int,--订单类型:1为正常下订流程的订单,2为团购,3拍卖的订单,4为合并的订单                                                               
@addMethod int,   --AddMethod 下订方式,1是会员在线下的订单,2是管理员代订                                    
@takeZtdID int,   --TakeZtdID 取货门店ID                                  
@ztdAdminID int,   --代订管理员ID
@AddIP varchar(50)='',     
@ErrorMessage varchar(2000)='' out,--错误信息提示        
@IsErrorFlag int =0 out--是否错误标识，<>0时，显示错误信息，并返回购物车界面 
AS
Begin

print('代销折扣，免运费，货到付款手续费，优惠券等功能还未实现')

 --设置订单的默认信息       
select @ErrorMessage='',@IsErrorFlag =0,@orderid=-1
                                
print('新订单的生成..')                               
declare @totalPrice decimal(18,2),@orlPdtPrice decimal(18,2),@pmtPdtPrice decimal(18,2),@pmtSubPrice decimal(18,2),@shipPrice decimal(18,2),@taxPrice decimal(18,2),@weight decimal(18,2),@cltCharge decimal(18,2)                                
declare @score int,@quantity int,@isAgentF int,@isShippingFree int,@ztdID int                                   
declare @sql nvarchar(1000),@orderNo nvarchar(30),@favourable nvarchar(500),@groupname nvarchar(20),@discount nvarchar(20),@agentFContent nvarchar(100),@addressID nvarchar(50)

print('构造地区ID字符串')
select @addressID=cast(@topAreaID as nvarchar(10))+','+cast(@subAreaID as nvarchar(10))+','+cast(@thirdAreaID as nvarchar(10))  
                 

print('获取会员对应会员组享受的折扣')
select @groupname=mg.groupname,@discount=mg.discount from member m,membergroup mg where m.groupid=mg.MemberGroupID and m.memberid=@memberid


print('商品信息')
SELECT p.ProductID,p.ProductNo,c.GoodsID,g.GoodsNo,
productname=case when c.productspecs<>'' then p.productname+'('+c.productspecs+')' else p.productname end,
c.ProductSpecs,p.Unit,p.MarketPrice,p.MemberPrice,
pmtprice=isnull(bl.limitprice,case when @discount<>'100' and p.IsDiscount=1 then g.memberprice*cast(@discount/100.00 as decimal(18,2)) else g.memberprice end),--优惠单价 
pmttip=case when bl.limitprice is not null then '(限时抢购价)' else case when @discount<>'100' and p.IsDiscount=1 then '('+@groupname+'折扣价)' else '会员价' end end,--优惠信息 
c.Quantity,(c.Quantity * g.Score)as Score,p.IsDiscount,c.UsedScore,bl.limitprice,
p.Weight*c.quantity as subweight,
g.memberprice*c.quantity as subprice,--单项原始小计金额
isnull(bl.limitprice,case when @discount<>'100' and p.IsDiscount=1 then g.memberprice*cast(@discount/100.00 as decimal(18,2)) else g.memberprice end)*c.quantity as pmtsubprice--单项优惠后小计金额
into #cartinfo
FROM ShoppingCart c,Goods g,Product p
left join BuyLimit bl      
on( p.productid=bl.productid and GetDate() Between bl.StartTime and bl.EndTime)
WHERE c.CartID = @CartID and c.Ptype =1 AND p.ProductID = c.ProductID AND c.GoodsID = g.GoodsID and g.ProductID = p.ProductID 
Order By c.RecordID

print('返回商品信息数据集')
select * from #cart
select @weight=sum(subweight),@score=sum(Score),@orlPdtPrice=sum(subprice),@pmtPdtPrice=sum(pmtsubprice),@pmtSubPrice=(sum(subprice)-sum(pmtsubprice)),@quantity=sum(Quantity) from #cartinfo

print('计算发票税金')
select @taxPrice=@pmtPdtPrice*@taxRate	--发票税金等于商品总额乘于税率

print('计算运费')
if(@payType=6)--到自提点提货,运费为0
begin
select @shipPrice=0
end
else--物流配送
begin
--18+(c(w/110)-1)*6
declare @exp nvarchar(100)--运费公式
select @exp=lower(ShippingExpression) from ShippingPrice where ShippingAreaID=@subAreaID and ShippingID=@shippingID 
select @exp=replace(@exp,'c','ceiling')
select @exp=replace(@exp,'w',cast(@weight as nvarchar(20)))
select top 0 shiprice=convert(money,0.0) into #shiprice
select @sql=N'insert into #shiprice select '+@exp
exec sp_executesql @sql
select @shipPrice=shiprice from #shiprice
end

print('统计订单总额')
select @totalPrice=@pmtPdtPrice+@shipPrice+@taxPrice-@advancePayment

print('生成订单编号')
declare @ordercount nvarchar(10)
Select @ordercount=count(orderid)+1 from orders Where DateDiff(dd,ordertime,GetDate())=0  --当天订单总数
select @orderNo=replace(replace(convert(varchar(13),getdate(),120),'-',''),' ','')                                  
select @orderNo=replace(@orderNo,'.','')   --转为2011012316                                    
select @orderNo=right(@orderNo,8) + right('000'+ cast(@ordercount as nvarchar(10)),4) --取时间的后8位+当天订单总数(若订单总数长度超过4,只取最后的4位) 

insert into orders(
OrderID,
MemberID,
OrderTime,
ShipTime,
BuyerName,
BuyerPhone,
BuyerEmail,
BuyerAddress,
BuyerPostalcode,
ReceiverName,
ReceiverPhone,
ReceiverEmail,
ReceiverAddress,
ReceiverPostalcode,
Remark,
TotalPrice,
ProductPrice,
CustomItemPrice,
Discount,
ShipPrice,
AdvancePayment,
PaymentType,
ShippingType,
Score,
Weight,
Quantity,
NeedInvoice,
TaxPrice,
CltCharge,
PayType,
Status,
ManageHistory,
LastModify,
OrderNo,
Code,
IsAgentF,
IsAgentFContent,
IsShippingFree,
Type,
Favourable,
ZtdNo,
IsToErp,
OrderType,
IsToMessage,
AddMethod,
AddressID,
UsedScore,
ScoreAmount
) 
values
(
@orderID,
@memberID,
getdate(),
@shippingTime,
'',
'',
'',
'',
'',
@rName,
@rPhone,
@rEmail,
@rAddress,
@rPostalcode,
@remark,
@totalPrice,
@pmtPdtPrice,
0,--配件价格
@discount,
@shipPrice,
@advancePayment,
0,--以前是paymentID,现在不用存支付方式ID,只需要存payType
@shippingID,
@score,
@weight,
@quantity,
@needInvoice,
@taxPrice,
@cltCharge,
@payType,
@status,
'',--订单管理日志
0,--最后更新时间
@orderNo,--订单编号
@code,
@isAgentF,
@agentFContent,
@isShippingFree,
@orderType,
@favourable,
@takeZtdID,
0,
0,
0,
1,
@addressID,
@usedScore,
@scoreAmount
)

End


GO
--优惠券使用情况列表
CREATE procedure [dbo].[listcoupons]
(
@pagerows int,        --每页行数    
@pageindex int,        --索引
@total nvarchar(400),    --条件
@sort nvarchar(50),    --排序
@rows int output --总行数
)
as
begin
set nocount on
declare 
@befrows int,
@sql_temp nvarchar(1000),
@sql_select nvarchar(400),
@sql_count nvarchar(100)
--先将数据放到临时表,并增加一个主键
set @sql_temp=N'select identity(int,1,1) as RowID, CM.CouponsCode,CM.MemberID,(select Name from Member where MemberID = CM.MemberID) as MemberName,CM.UsedTimes,CM.AddTime,CM.GetMethod,CM.Status As CouponsMemberStatus,C.CouponsID,C.CouponsName,C.Type,C.Status as CouponsStatus,P.TimeBegin,P.TimeEnd,isnull(CUI.CouponsUsedItemsID,0) as CouponsUsedItemsID,CUI.UseTime into ##temp_coupons from CouponsMember as CM left join Coupons as C on CM.CouponsID = C.CouponsID left join Promotion as P on C.PromotionID = P.PromotionID left join CouponsUsedItems as CUI on CUI.CouponsCode = CM.CouponsCode where ' + @total+' '+@sort+''
set @befrows=@pagerows*(@pageindex-1)
--查询
set @sql_select=N'select top '+cast(@pagerows as nvarchar(50))+' * from ##temp_coupons where RowID not in (select top '+cast(@befrows as nvarchar(50))+' RowID from ##temp_coupons) '
-------总条数------
set @sql_count=N'select @rows=count(RowID) from ##temp_coupons'
EXEC (@sql_temp)
EXEC (@sql_select)
exec sp_executesql @sql_count,N'@rows int out',@rows out

if object_id('tempdb..##temp_coupons') is not null
drop table ##temp_coupons

select  @rows
return @rows
end
GO
/****** 对象:  StoredProcedure [dbo].[listpagetext]    脚本日期: 04/09/2012 18:25:31 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[listpagetext]
(
@pagerows int,        --每页行数    
@pageindex int,        --索引
@tab nvarchar(250),    --表名
@keyid nvarchar(50),    --主键
@total nvarchar(4000),    --条件
@sort nvarchar(50),    --排序
@kid nvarchar(500),    --列名
@tt  nvarchar(50), --针对获得总条数时需要的特殊条件，一般为*
@rows int output --总行数
)
as
begin
set nocount on
declare 
@befrows int,
@sql nvarchar(4000)
set @befrows=@pagerows*(@pageindex-1)
set @sql='select top '+cast(@pagerows as nvarchar(50))+' '+@kid+' from '+@tab+' where '+@total+' and '+@keyid+' not in (select top '+cast(@befrows as nvarchar(50))+' '+@keyid+' from '+@tab+' where '+@total+' '+@sort+' )   '+@sort+''
insert [log]([content])values(@sql)

EXEC (@sql)
--select *from [log] order by addtime desc
-------总条数------
set @sql=N'select @rows=count('+@tt+') from '+@tab+' where '+@total+'  '+''
exec sp_executesql @sql,N'@rows int out',@rows out
select  @rows
return @rows
end


GO
/****** 对象:  StoredProcedure [dbo].[logger]    脚本日期: 04/09/2012 18:25:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[logger]
@content varchar(200)
AS
BEGIN
	insert into log ([content]) values (@content)
END

GO
/****** 对象:  StoredProcedure [dbo].[LookCartProc]    脚本日期: 04/09/2012 18:25:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[LookCartProc] 
@cartid nvarchar(50),
@productid int=0,
@goodsid int=0,
@spec nvarchar(100)='',--商品规格
@qty int=1,--数量
@ptype int=1,--1添加商品,2添加积分兑换礼品
@memberid int=-1,
@scorerate decimal(18,2)--积分兑换货币比率
AS
BEGIN
if @productid>0
begin
--添加商品或积分兑换的礼品到购物车
print('添加商品或积分兑换的礼品')
if exists(select RecordID from ShoppingCart where ProductID=@productID and CartID=@cartID and GoodsID=@goodsID and ptype=@ptype)
update ShoppingCart set quantity=quantity+@qty where ProductID=@productID and CartID=@cartID and GoodsID=@goodsID and ptype=@ptype
else
insert into ShoppingCart 
(CartID,Quantity,ProductID,Items,AddTime,ProductSpecs,GoodsID,Ptype) 
values 
(@cartid,@qty ,@productid,'',getdate(),@Spec,@goodsid,@ptype)
end

print('获取会员对应会员组享受的折扣')
declare @groupid int,--会员组ID
@groupname nvarchar(20),--会员组名称
@discount decimal(18,2)--会员组折扣
select @groupid=groupid,@groupname=mg.groupname,@discount=cast(mg.discount/100.00 as decimal(18,2)) from member m,membergroup mg where m.groupid=mg.MemberGroupID and m.memberid=@memberid
select @groupid,@discount
--declare @cartid nvarchar(100)
--select @cartid='10a2fd6e-e9c4-4142-a9d8-41cf9c763f6c'
--1.购物车信息
select       
p.productid,p.productno,p.productname,gg.marketprice,gg.memberprice,gg.weight,      
c.CartID,c.quantity,
gg.weight*c.quantity subweight,      
g.pmtprice,
--isnull(g.pmtprice,case when @discount<>'100' and p.IsDiscount=1 then gg.memberprice*cast(@discount/100.00 as decimal(18,2)) else null end) pmtprice,--优惠单价
isnull(g.pmtprice,gg.memberprice)*c.quantity SubMoney,--小计金额      
(gg.memberprice-isnull(g.pmtprice,gg.memberprice))*c.quantity LessMoney,--优惠金额      
 g.pmtname,g.RuleID ,g.RuleName,g.BasicType,g.SubType,      
convert(varchar(200),'') remark , 
gg.GoodsID,p.IsDiscount,1 IsDlvUnit,1 DlvUnit,MiniBuyNum,gg.Score,p.usescore,0 StowageID,1 IsOfferInvoice, 
RecordID,ProductSpecs  
,g.pmtid--活动ID   
into #cart      
from
ShoppingCart c(nolock),goods gg(nolock),product p(nolock)     
left join PmtGoodsList g      
on( p.productid=g.productid and g.BasicType='goods' and g.SubType in('discount','specialprice')--一个商品只能作一个特价或折扣
and charindex(','+convert(nvarchar(10),@groupid)+',',','+g.GroupIDs+',')>0--允许参与优惠活动的会员组才可以享受优惠
)       
where
c.productid=p.productid
and gg.goodsid=c.goodsid--增加多维规格功能  
and p.productid=gg.productid      
and c.quantity>0
and c.ptype=1--商品      
and c.cartid=@cartid

update #cart set pmtprice=memberprice*@discount,submoney=submoney*@discount,lessmoney=(memberprice-memberprice*@discount)*quantity where isnull(pmtid,0)=0 and IsDiscount=1 and @discount<>'100'

--2.商品购买数量控制 
select b.*      
into #MemberBookProduct      
from MemberBookPmtGoods b(nolock),#cart c(nolock)      
where 
b.RuleID=c.RuleID and c.productid=b.productid 

--2.1购买总数量限制      
select p.RuleID,p.productid,g.PmtNumber maxgoodsnumber,sum(p.quantity) goodsnumber      
into #MemberBookProduct_a--购买总数统计表      
from #MemberBookProduct p(nolock),PmtGoods g(nolock)      
where g.ruleid=p.ruleid      
and g.productid=p.productid      
and g.PmtNumber>0--限制数量
group by p.RuleID,p.productid,g.PmtNumber      
having sum(p.quantity)>=g.PmtNumber      
      
--2.2会员购买数量限制      
select p.ruleid,p.productid,memberid ,g.LimitedNumber maxmembernumber,sum(quantity) membernumber      
into #MemberBookProduct_b--个人购买统计表      
from #MemberBookProduct p(nolock) ,PmtGoods g(nolock)      
where       
g.ruleid=p.ruleid      
and g.productid=p.productid      
and g.LimitedNumber>0--限制数量      
and memberid=@memberid      
group by  p.ruleid,p.productid,memberid ,g.LimitedNumber        
having sum(p.quantity)>=g.LimitedNumber      
      
--2.3汇总      
--2.3.1      
update c set c.quantity=0,SubMoney=0,LessMoney=0, remark='此商品已经抢购完,<span style="color:Green;">谢谢您的支持，请在下次购买</span>'                
from #cart c,#MemberBookProduct_a a(nolock)                            
where                     
c.ruleid=a.ruleid                            
and c.productid=a.productid      
      
--2.3.2      
update c set c.quantity=0,SubMoney=0,LessMoney=0, remark='您已超过此商品最大购买抢购量:'+convert(varchar(8),a.maxmembernumber)+',<span style="color:Green;">谢谢您的支持，请在下次购买</span>'              
from #cart c,#MemberBookProduct_b a(nolock)                            
where                            
c.ruleid=a.ruleid                            
and c.productid=a.productid         
      
--2.3.3     
update c set c.quantity=0,SubMoney=0,LessMoney=0, remark='您已超过此商品最大购买抢购量:'+convert(varchar(8),a.LimitedNumber)+',<span style="color:Green;">请修改数量</span>'              
from #cart c,PmtGoods a(nolock)                            
where                            
c.ruleid=a.ruleid                            
and c.productid=a.productid                            
and ((c.quantity> a.PmtNumber and  a.PmtNumber>0)                             
or c.quantity>a.LimitedNumber and a.LimitedNumber>0) 
    

--3.1订单信息汇总                           
print('购物车汇总，获取参与促销活动汇总信息')                        
--drop table  #orderinfo                 
select l.ruleid,sum(SubMoney) totalprice,sum(quantity) totalnumber                            
into #orderinfo                            
from #cart c(nolock),PmtGoodsList l(nolock)                            
where                         
1=1                        
and                         
c.productid=l.productid        
and c.goodsid=l.goodsid                      
and l.SubType='gift'   --礼品换购信息                          
group by l.ruleid                   
                                           
                            
--3.2获取赠品商品信息          
print('--3.2获取赠品商品信息  ')                         
if object_id('tempdb.dbo.#gift') is not null                            
begin       
drop table #gift                            
end                                
select  floor(                        
case when isautoAdded=1 then                            
case when r.BasicType='orders' then o.totalprice                            
when r.BasicType='goods' then o.totalnumber end/minvalue  --订单满额规格可能有问题
else 1 end) giftnumber,--可获礼品数量                            
convert(varchar(200),' ') giftremark, r.BasicType,g.SubType,                       
g.ID,g.PmtName,g.RuleID,g.RuleNo,                        
g.RuleName,g.productid,g.goodsid,g.productname,                        
g.categoryid,g.brandid,g.brandname,g.usescore,g.score,                        
g.marketprice,g.memberprice,g.PmtPrice,g.stowageid,                        
g.PmtNumber,g.LimitedNumber,g.IsLimited,g.maxnumber,g.isselected,                        
g.gifttype,g.groupname,g.addtime,g.status,                        
--g.adduser,g.deltime,g.deluser,
g.remark,
r.PmtID                       
into #gift                             
from #orderinfo o(nolock),PmtRule r(nolock),PmtGifts g(nolock),Product p(nolock)   -----------------------------这里为什么要联商品表product????????????                         
where                             
o.ruleid=r.ruleid                          
and p.productid=g.productid                          
and g.ruleid=r.ruleid                            
and r.SubType='gift'                            
and minvalue                            
<=case when r.BasicType='orders' then o.totalprice               
when r.BasicType='goods' then o.totalnumber end--起始条件                            
and (  maxvalue=0 or  isautoAdded=1 or                          
convert(money,maxvalue)>case when r.BasicType='orders' then o.totalprice                            
when r.BasicType='goods' then o.totalnumber end--最大条件                            
)

--4.礼品数量限制                    
if object_id('tempdb.dbo.#MemberBookGift') is not null                            
begin                            
drop table #MemberBookGift                            
end                            
select b.*                            
into #MemberBookGift                            
from MemberBookPmtGoods b(nolock),#gift c(nolock)                            
where b.RuleID=c.RuleID                            
and c.productid=b.productid                            
                            
--4.1总数限制                                                     
print('--4.1总数限制   ')                           
if object_id('tempdb.dbo.#MemberBookGift_a') is not null                            
begin                            
drop table #MemberBookGift_a                            
end           
select p.RuleID,p.productid,l.PmtNumber,sum(p.quantity) SaleNumber                            
into #MemberBookGift_a                            
from #MemberBookGift p(nolock),PmtGifts l(nolock)                            
where l.RuleID=p.RuleID                            
and l.productid=p.productid                            
and l.PmtNumber>0--有限制数量                            
group by p.RuleID,p.productid,l.PmtNumber                            
having sum(p.quantity)>=l.PmtNumber                      
                            
--4.2个人数量限制                           
print('--4.2个人数量限制 ')                           
if object_id('tempdb.dbo.#MemberBookGift_b') is not null                            
begin                            
drop table #MemberBookGift_b                            
end                            
select p.RuleID,p.productid,memberid,l.LimitedNumber,sum(quantity) PersonalNumber                            
into #MemberBookGift_b                            
from #MemberBookGift p(nolock) ,PmtGifts l(nolock)                            
where                             
l.RuleID=p.RuleID                            
and l.productid=p.productid                            
and l.LimitedNumber>0--有限制个人购买数量                            
and memberid=@memberid                            
group by  p.RuleID,p.productid,memberid,l.LimitedNumber                              
having sum(p.quantity)>=l.LimitedNumber 
                           
--4.3赠品信息汇总 
--4.3.1                           
print('4.3.1赠品信息,此礼品已经送完完')                          
update c set giftnumber=0,giftremark='此礼品已经送完'                            
from #gift c,#MemberBookGift_a a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                        
--4.3.2                            
print('4.3.2赠品信息,你已超过此礼品的最大量')                          
update c set giftnumber=0,giftremark='你已超过此礼品的最大量!'                            
from #gift c,#MemberBookGift_b a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                            
--4.3.3                           
print('4.3.3 赠品信息,最后一次仍送出')                           
update c set giftnumber=a.LimitedNumber,giftremark='最后一次仍送出!'                            
from #gift c,PmtGoods a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                            
and ((c.giftnumber> a.PmtNumber and  a.PmtNumber>0)                             
or c.giftnumber>a.LimitedNumber and a.LimitedNumber>0) 

--4.4 赠品库存控制    
update c set giftnumber=0,giftremark='很抱歉，此赠品已经送完!'                            
from #gift c,goods g(nolock)                            
where            
c.goodsid=g.goodsid    
and g.Storage<=0

--5 订单总金额优惠信息     
print('--5订单总金额优惠信息 ')                           
select top 0  TotalMoney=100, LessMoney=0,ruleid=' ' ,rulename=' ' ,moneyremark=' '                           
into #orderpromotion

--6 显示信息

--6.1 商品购物车表                            
delete from goodscart where cartid=@cartid                                                     
insert into goodscart(                     
cartid,productid,productno,marketprice,memberprice,weight,                            
pmtprice,quantity,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,remark,                        
GoodsID, IsDlvUnit, DlvUnit,MiniBuyNum,Score,                        
StowageID,IsOfferInvoice,RecordID,ProductSpecs                      
,pmtid,IsDiscount,UseScore,ScoreMoney                          
)                            
select @cartid,productid,productno,marketprice,memberprice,weight,                            
pmtprice,quantity,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,remark,                        
GoodsID, IsDlvUnit, DlvUnit,MiniBuyNum,Score*quantity,                        
StowageID,IsOfferInvoice,RecordID,ProductSpecs                        
,pmtid,IsDiscount,UseScore,UseScore*@scorerate                              
from  #cart c(nolock)

--6.2礼品购物车表 
--description:统计原先换购的礼品和积分兑换的礼品放入#oldgift，清空礼品购物车中非换购和积分兑换的礼品，

--6.2.1保证原先选择的礼品不会被删除                         
print('保证原先选择的礼品不会被删除')                        
select  c.*                         
into  #oldgift                        
from giftscart c(nolock),#gift t(nolock)                         
where                         
(isnull(c.ruleid,0)=0 and c.UseScore>0 and c.cartid=@cartid)--积分兑换的礼品                        
or
(c.addtime>getdate()-1                        
and c.productid=t.productid                         
and c.giftnumber=t.giftnumber                        
and c.giftnumber>0--礼品数量为0的不能保留                        
and c.isSystemAdd=0--礼品非系统自动添加                        
and c.cartid=@cartid)
                         
print('商品数量进行了修改，需要删除变化礼品信息，')                        
delete g                         
from giftscart g(nolock)                        
where                         
1=1                        
and g.RuleID not in(            
select o.ruleid                          
from  #oldgift o(nolock) 
where cartid=@cartid                        
)                                                
and g.cartid=@cartid  

--6.2.2 单个礼品规则，且价格为0的，自动添加到礼品表中。                        
--选出规则中只有单个礼品，且价格为0的规则,且上次保留的礼品信息                                                  
print('选出规则中只有单个礼品，且价格为0的规则,且不是上次保留的礼品信息')                        
select g.ruleid                        
into #SinpleGift                        
from #gift g                         
where                         
1=1                         
and g.ruleid not in(                         
select o.ruleid                         
from  #oldgift o(nolock) where cartid=@cartid                        
)                        
and g.pmtprice=0                        
group by g.ruleid                        
having count(g.ruleid)=1

--6.2.3 系统自动添加的礼品信息                                                                 
print('系统自动添加的礼品信息')                                      
insert into giftscart(                            
cartid,productid,productno,marketprice,memberprice                            
,pmtprice,giftnumber,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,giftremark                         
,productname,isSystemAdd,pmtid,UseScore                            
)                            
select @cartid,c.productid,p.productno,c.marketprice,c.memberprice                            
,c.pmtprice,giftnumber,c.memberprice*giftnumber submoney,c.pmtprice*giftnumber lessmoney, --有疑惑                          
pmtname,c.ruleid,basictype,subtype,giftremark                        
,p.productname ,1 isSystemAdd,c.pmtid,0--非积分兑换，使用积分为0                                
from  #gift c(nolock) ,#SinpleGift s(nolock),product p(nolock)                        
where 
c.ruleid=s.ruleid and c.productid=p.productid                        
                        
--6.2.4 删除系统自动添加的礼品信息                                              
print('删除系统自动添加的礼品信息')                        
delete c                        
from  #gift c(nolock) ,#SinpleGift s(nolock)                        
where c.ruleid=s.ruleid   

--6.2.5 可选礼品信息表
print('可选礼品信息表')                        
delete from GiftsCart_temp where cartid=@cartid                        
insert into GiftsCart_temp(                            
cartid,productid,productno,marketprice,memberprice                            
,pmtprice,giftnumber,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,giftremark,productname                  
)                         
select @cartid,p.productid,p.productno,c.marketprice,c.memberprice                            
,pmtprice,c.giftnumber,c.memberprice*giftnumber submoney,c.pmtprice*giftnumber lessmoney,                            
c.pmtname,c.ruleid,basictype,subtype,giftremark,p.productname              
from  #gift c(nolock),product p(nolock)                        
where c.productid=p.productid

                           
                            
--7 购物车信息
                            
--7.1显示购物车商品信息      
print('7.1显示购物车商品信息  ')                          
select * from                             
#cart c(nolock)
                           
--7.2显示购物车礼品信息                                                     
select c.* , r.rulename                        
from giftscart c(nolock),pmtrule r(nolock)                        
where c.ruleid = r.ruleid                        
and cartid=@cartid                     
                       
--7.3需要用户自己选择的礼品，需要会员自己决定手工将礼品加入到礼品表中 
if coalesce(@memberid, -1)=-1                          
--if(len(@memberid)=0 or @memberid=-1)--会员未登录不显示礼品信息                            
begin                                              
select top 0 c.* ,r.rulename from giftcarts_temp c,pmtrule r(nolock) where cartid=@cartid and c.ruleid = r.ruleid                                             
end
                            
else                             
begin                         
select c.* ,r.rulename from giftscart_temp c,pmtrule r(nolock) where cartid=@cartid and c.ruleid = r.ruleid                        
                        
end                             
                            
--7.4订单金额优惠信息,订单优惠金额暂时先不做                                        
print('7.4订单金额优惠信息,订单优惠金额暂时先不做')                            
select top 1 * from #orderpromotion 

select * from goodscart                          
select * from giftscart
                        
print('订单商品品种数、商品总数量、总金额、总获得积分、总使用积分、总的积分抵扣金额、总优惠的金额')                         
--订单信息                         
select cartid,count(productid) goodsnumber,sum(quantity) totalnumber ,sum(subweight) totalweight,sum(submoney-scoremoney) totalmoney ,sum(score) totalscore,sum(usescore) usedscore,sum(scoremoney) totalscoremoney,sum(LessMoney) totallessmoney                        
into #ordermessage                      
from                        
(                        
select cartid,productid,quantity,subweight,submoney,Score,UseScore,ScoreMoney,LessMoney                         
from goodscart g(nolock)                        
where cartid=@cartid                        
union                        
select cartid,productid,giftnumber,subweight,submoney, 0 Score,UseScore,0 ScoreMoney,LessMoney                         
from giftscart g(nolock)                        
where cartid=@cartid                        
) as t                        
group by cartid                        
--订单商品品种数、商品总数量、总金额、总积分、总优惠的金额                      
select *                      
from #ordermessage o(nolock)                      
                      
--declare @shipfeer money,@CouponValue money,
declare @ordermoney money                      
--select @shipfeer=0                  
--select @CouponValue=0                      
select @ordermoney=(select top 1 totalmoney from #ordermessage)                      
                      
/*
print('--10.5运费  ')                                            
delete from ShipCart where cartid=@cartid                      
insert into ShipCart(cartid,shipfeer,memberid)                       
values(@cartid,@shipfeer,@memberid)                      
                    
select shipfeer=@shipfeer                      
print('--10.6优惠券')                      
select   CouponValue ,CouponName                      
into #CouponCart                      
from CouponCart c(nolock),CouponDetail d(nolock)                      
where c.CartID=@CartID                      
and d.CouponID=c.CouponID                   
and c.CouponID in (select CouponID from goodscart(nolock) where cartid=@cartid)                    
select * from #CouponCart                      
select @CouponValue=(select  isnull(sum(CouponValue),0)  from #CouponCart)                      
*/
              
print('应付款')                      
--select neepaymoney=@ordermoney+@shipfeer-@CouponValue                      
select neepaymoney=@ordermoney 

/*                   
print('10.8参与活动或者是其它信息')                     
if object_id('tempdb.dbo.#activelist_temp') is not null                    
begin                    
drop table #activelist_temp                    
end                    
create table #activelist_temp                    
(                    
activename varchar(1000) default '',                    
tipmessage varchar(200) default ''                    
)                    
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;">满50元可使用5元优惠券（促销商品除外）</span>',tipmessage='满50元可使用5元优惠券'                     
                    
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;">满100元可使用10元优惠券（促销商品除外）</span>',tipmessage='满100元可使用10元优惠券'                     
                
                
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;"><a href="products/product-1100530.html">5L金龙鱼花生浓香调和油特价每人限购1瓶</a></span>',tipmessage='5L金龙鱼花生浓香调和油特价每人限购1瓶,数量有限'      
where getdate() between getdate()-5 and  '2010-12-01'                 
                
select  *  from #activelist_temp  
*/

END

GO
/****** 对象:  StoredProcedure [dbo].[max1]    脚本日期: 04/09/2012 18:25:34 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[max1]
As
BEGIN
	select cast(substring(Period,12,(select len(Period)-11)) as int) as aa from Card
END
GO
/****** 对象:  StoredProcedure [dbo].[MemberLogin_Proc]    脚本日期: 04/09/2012 18:25:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
create PROCEDURE [dbo].[MemberLogin_Proc] 
@name nvarchar(50),
@password nvarchar(50),
@result int =0 out
AS
begin
declare @memberID int
declare @status int
select @memberID=MemberID,@status=Status FROM Member WHERE ([Name]=@name OR Email=@name) AND [Password] = @password AND Status >= 0
if(@memberID is null)
select @result = -1
else if(@status=0)
select @result=0
else
select @result=@memberID
end
 
GO
/****** 对象:  StoredProcedure [dbo].[P_BuyLimit]    脚本日期: 04/09/2012 18:25:34 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[P_BuyLimit] (@productIDs nvarchar(1000),@limitPrices nvarchar(4000),@startTimes nvarchar(4000),@endTimes nvarchar(4000),@quantitys nvarchar(1000),@catID nvarchar(30))
As
BEGIN
	Delete From BuyLimit Where CategoryID = @catID
	--Update Product Set IsBuyLimited = 0 Where CategoryID = @catID
	IF(@productIDs <> '')
	Begin
		Declare @productID int
		Declare @limitPrice decimal(18,2)
		Declare @startTime datetime
		Declare @endTime datetime
		Declare @quantity int
		
		Declare @i int,@buyLimitID int
		Set @productIDs = dbo.f_l_removesign(dbo.f_addsign(dbo.f_r_removesign(RTRIM(LTRIM(@productIDs)))))
		Set @limitPrices = dbo.f_l_removesign(dbo.f_addsign(dbo.f_r_removesign(RTRIM(LTRIM(@limitPrices)))))
		Set @startTimes = dbo.f_l_removesign(dbo.f_addsign(dbo.f_r_removesign(RTRIM(LTRIM(@startTimes)))))
		Set @endTimes = dbo.f_l_removesign(dbo.f_addsign(dbo.f_r_removesign(RTRIM(LTRIM(@endTimes)))))
		Set @quantitys = dbo.f_l_removesign(dbo.f_addsign(dbo.f_r_removesign(RTRIM(LTRIM(@quantitys)))))
		
		While(@productIDs <> '')
		BEGIN
			Set @i = charindex(',',@productIDs)
			Set @productID = substring(@productIDs,1,@i-1)
			Set @productIDs = substring(@productIDs,@i+1,len(@productIDs))
			
			Set @i = charindex(',',@limitPrices)		
			Set @limitPrice = substring(@limitPrices,1,@i-1)
			Set @limitPrices = substring(@limitPrices,@i+1,len(@limitPrices))
			
			Set @i = charindex(',',@startTimes)
			Set @startTime = substring(@startTimes,1,@i-1) + ':00'
			Set @startTimes = substring(@startTimes,@i+1,len(@startTimes))
			
			Set @i = charindex(',',@endTimes)
			Set @endTime = substring(@endTimes,1,@i-1) + ':59'
			Set @endTimes = substring(@endTimes,@i+1,len(@endTimes))
			
			Set @i = charindex(',',@quantitys)
			Set @quantity = substring(@quantitys,1,@i-1)
			Set @quantitys = substring(@quantitys,@i+1,len(@quantitys))
			
			Select @buyLimitID = IsNull(Max(BuyLimitID)+1,1) From BuyLimit
			INSERT INTO BuyLimit (BuyLimitID,ProductID,LimitPrice,StartTime,EndTime,Quantity,CategoryID) VALUES (@buyLimitID,@productID,@limitPrice,@startTime,@endTime,@quantity,@catID)
		END
	END
END
GO
/****** 对象:  StoredProcedure [dbo].[P_Category_Update_CategoryNo]    脚本日期: 04/09/2012 18:25:35 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE procedure [dbo].[P_Category_Update_CategoryNo]  @CategoryNo decimal(30,0),@newParentNo decimal(30,0),@mul decimal(30,0)
As
BEGIN
	Declare @newCategoryNo decimal(30,0)
	SELECT @newCategoryNo = ISNULL(Max(CategoryNo),@newParentNo * @mul) + 1 FROM Category Where CategoryNo Between @newParentNo * @mul And ((@newParentNo + 1) * @mul - 1)
	
	Declare @sql nvarchar(200)
	Set @sql = 'Update Category Set CategoryNo = cast(' + cast(@newCategoryNo as nvarchar(30)) + ' as nvarchar(30)) + substring(cast(CategoryNo as nvarchar(30)),len(' + cast(@CategoryNo as nvarchar(30)) + ') + 1,len(CategoryNo)) where CategoryNo like ''' + Cast(@CategoryNo as nvarchar(30)) + '%'''
	print @sql
	Exec sp_executesql @sql
	Exec [dbo].[P_Category_Update_ParentNo]  @newCategoryNo,@mul
END


GO
/****** 对象:  StoredProcedure [dbo].[P_Category_Update_ParentNo]    脚本日期: 04/09/2012 18:25:35 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

CREATE procedure [dbo].[P_Category_Update_ParentNo]  @CategoryNo decimal(30,0),@mul decimal(30,0)
As
BEGIN
	Declare @sql nvarchar(200)
	Set @sql = 'update Category set ParentNo = cast(CategoryNo/' + cast(@mul as nvarchar(5)) + ' + 0.5 as decimal(30,0)) - 1 Where CategoryNo like ''' + Cast(@CategoryNo as nvarchar(30)) + '%'''
	Exec sp_executesql @sql
END


GO
/****** 对象:  StoredProcedure [dbo].[p_get_category_path]    脚本日期: 04/09/2012 18:25:36 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE procedure [dbo].[p_get_category_path]
@cid int,--分类ID
@brandid int,--品牌ID
@result nvarchar(300) out
as
begin
	declare @tmpID int
	declare @categoryno nvarchar(20)
	declare @name nvarchar(20)
	declare @parentno nvarchar(20)
	declare @inbar int
	declare @catno nvarchar(20)
	set @result = '<a href="/index.html">首页</a> > '
	select @catno=categoryno from category where categoryid = @cid
	declare mycursor cursor 
	for
	select categoryid,categoryno,name,parentno,inbar--,len(categoryid)
	from category c(nolock)
	where 
	left(@catno,len(categoryno))=categoryno and categoryid <>0
	order by len(categoryno)
	
	open mycursor
	fetch next from mycursor into @tmpID,@categoryno,@name,@parentno,@inbar
	while @@fetch_status = 0
	begin
--		if @parentno = '1' and @inbar = 1
--		begin
--			set @result = @result + '<a href="/channel-' + cast(@tmpID as varchar(20)) + '.html">' + rtrim(@name) + '</a> > '
--		end
--		else
		begin
			set @result = @result + '<a href="/categorys-' + cast(@tmpID as varchar(20)) + '.html">' + rtrim(@name) + '</a> > '
		end
		fetch next from mycursor into @tmpID,@categoryno,@name,@parentno,@inbar
	end
	close mycursor        
	deallocate mycursor 
	set @result = left(@result,len(@result)-2)
	if @brandid > 0
	begin
		declare @brandname nvarchar(15)
		select @brandname = BrandName from Brand where BrandID = @brandid
		if @brandname is not null
			set @result = @result + '  > '+ @brandname
	end
end



GO
/****** 对象:  StoredProcedure [dbo].[P_PmtGenCoupons]    脚本日期: 04/09/2012 18:25:36 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE procedure [dbo].[P_PmtGenCoupons] (@promotionID int,@couponsIDs nvarchar(4000))
As
BEGIN
	Delete From PmtGenCoupons Where PromotionID = @promotionID
	Declare @couponsID int
	
	Declare @i int,@pmtGenCouponsID int
	Set @couponsIDs = dbo.f_l_removesign(dbo.f_addsign(dbo.f_r_removesign(RTRIM(LTRIM(@couponsIDs)))))
	While(@couponsIDs <> '')
	BEGIN
		Set @i = charindex(',',@couponsIDs)
		Set @couponsID = substring(@couponsIDs,1,@i-1)
		Set @couponsIDs = substring(@couponsIDs,@i+1,len(@couponsIDs))
		Select @pmtGenCouponsID = IsNull(Max(PmtGenCouponsID)+1,1) From PmtGenCoupons
		INSERT INTO PmtGenCoupons (PmtGenCouponsID,PromotionID,CouponsID,Status) VALUES (@pmtGenCouponsID,@promotionID,@couponsID,1)
	END
END
GO
/****** 对象:  StoredProcedure [dbo].[P_PmtProduct]    脚本日期: 04/09/2012 18:25:37 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE procedure [dbo].[P_PmtProduct] (@promotionID int,@productIDs nvarchar(4000))
As
BEGIN
	Delete From PmtProduct Where PromotionID = @promotionID
	Declare @productID int
	
	Declare @i int,@pmtProductID int
	Set @productIDs = dbo.f_l_removesign(dbo.f_addsign(dbo.f_r_removesign(RTRIM(LTRIM(@productIDs)))))
	While(@productIDs <> '')
	BEGIN
		Set @i = charindex(',',@productIDs)
		Set @productID = substring(@productIDs,1,@i-1)
		Set @productIDs = substring(@productIDs,@i+1,len(@productIDs))
		Select @pmtProductID = IsNull(Max(PmtProductID)+1,1) From PmtProduct
		INSERT INTO PmtProduct (PmtProductID,PromotionID,ProductID) VALUES (@pmtProductID,@promotionID,@productID)
	END
END
GO
/****** 对象:  StoredProcedure [dbo].[P_PromotionMemberGroup]    脚本日期: 04/09/2012 18:25:37 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE procedure [dbo].[P_PromotionMemberGroup] (@promotionID int,@memberGroupIDs nvarchar(200))
As
BEGIN
	Delete From PromotionMemberGroup Where PromotionID = @promotionID
	Declare @memberGroupID int
	
	Declare @i int,@promotionMemberGroupID int
	Set @memberGroupIDs = dbo.f_l_removesign(dbo.f_addsign(dbo.f_r_removesign(RTRIM(LTRIM(@memberGroupIDs)))))
	While(@memberGroupIDs <> '')
	BEGIN
		Set @i = charindex(',',@memberGroupIDs)
		Set @memberGroupID = substring(@memberGroupIDs,1,@i-1)
		Set @memberGroupIDs = substring(@memberGroupIDs,@i+1,len(@memberGroupIDs))
		Select @promotionMemberGroupID = IsNull(Max(PromotionMemberGroupID)+1,1) From PromotionMemberGroup
		INSERT INTO PromotionMemberGroup (PromotionMemberGroupID,PromotionID,MemberGroupID) VALUES (@promotionMemberGroupID,@promotionID,@memberGroupID)
	END
END
GO
/****** 对象:  StoredProcedure [dbo].[P_VideoCat_Update_CategoryNo]    脚本日期: 04/09/2012 18:25:38 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE procedure [dbo].[P_VideoCat_Update_CategoryNo]  @oldCategoryNo decimal(30,0),@newParentNo decimal(30,0),@mul decimal(30,0)
As
BEGIN
	Declare @newCategoryNo decimal(30,0)
	SELECT @newCategoryNo = ISNULL(Max(CategoryNo),@newParentNo * @mul) + 1 FROM VideoCat Where CategoryNo Between @newParentNo * @mul And ((@newParentNo + 1) * @mul - 1)

	--更新CategoryNo
	Declare @sql nvarchar(500)
	Set @sql = 'Update VideoCat Set CategoryNo = cast(' + cast(@newCategoryNo as nvarchar(30)) + ' as nvarchar(30)) + substring(cast(CategoryNo as nvarchar(30)),len(' + cast(@oldCategoryNo as nvarchar(30)) + ') + 1,len(CategoryNo)) where CategoryNo like ''' + Cast(@oldCategoryNo as nvarchar(30)) + '%'''

	--更新ParentNo
	Declare @sqlUpdatePNo nvarchar(500)
	set @sqlUpdatePNo = 'Update VideoCat set ParentNo = ceiling((CategoryNo/' + Cast(@mul as nvarchar(30)) + ' + 0.5)-1) where CategoryNo like ''' + Cast(@newCategoryNo as nvarchar(30)) + '%'''

	--更新Depth
	Declare @sqlUpdateDepth nvarchar(200)
	set @sqlUpdateDepth = 'Update VideoCat set Depth = (select isnull((select Depth from VideoCat where CategoryNo = ceiling((CategoryNo/' + Cast(@mul as nvarchar(30)) + ' + 0.5)-1)),0) + 1) where CategoryNo like ''' + Cast(@newCategoryNo as nvarchar(30)) + '%'''

	Exec sp_executesql @sql
	Exec sp_executesql @sqlUpdatePNo
	Exec sp_executesql @sqlUpdateDepth
END
GO
/****** 对象:  StoredProcedure [dbo].[pr_backup_db]    脚本日期: 04/09/2012 18:25:38 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
create proc [dbo].[pr_backup_db]
@flag varchar(20) out,
@backup_db_name varchar(128),
@filename varchar(1000)  --路径＋文件名字
as
declare @sql nvarchar(4000),@par nvarchar(1000)
if not exists(
 select * from master..sysdatabases
  where name=@backup_db_name
  )
begin
 select @flag='数据库不存在'  /*数据库不存在*/
 return
end
else
begin
 if right(@filename,1)<>'\' and charindex('\',@filename)<>0
 begin
  select @par='@filename varchar(1000)'
  select @sql='BACKUP DATABASE '+@backup_db_name+' to disk=@filename with init'
  execute sp_executesql @sql,@par,@filename
  select @flag='ok'
  return
 end
 else
 begin
  select @flag='路径错误'  /*参数@filename输入格式错误*/
  return
 end
end

GO
/****** 对象:  StoredProcedure [dbo].[Pr_BackupDataBase]    脚本日期: 04/09/2012 18:25:39 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
/*输入参数,执行备份过程的过程*/ 
CREATE PROCEDURE [dbo].[Pr_BackupDataBase]
  @dbname varchar(255),/*需要备份的数据库名*/
  @path varchar(255),/*数据库备份的完整路径*/
  @flag varchar(20) out
 As
execute pr_backup_db @flag out,@dbname,@path

GO
/****** 对象:  StoredProcedure [dbo].[pr_insertData]    脚本日期: 04/09/2012 18:25:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[pr_insertData]
(
@sqltext nvarchar(4000)
)
as
begin
set nocount on
	EXEC (@sqltext)
	select @@identity as tid
end

GO
/****** 对象:  StoredProcedure [dbo].[Pr_RunSQL]    脚本日期: 04/09/2012 18:25:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Pr_RunSQL]
(
	@sql nText
)
as
	EXEC (@sql)

GO
/****** 对象:  StoredProcedure [dbo].[pr_update_order_status]    脚本日期: 04/09/2012 18:25:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create procedure [dbo].[pr_update_order_status](@orderno nvarchar(50),@status int)
--WITH ENCRYPTION
as
begin
	update orders set status = @status where orderno = @orderno
end

GO
/****** 对象:  StoredProcedure [dbo].[pr_update_product_storage]    脚本日期: 04/09/2012 18:25:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[pr_update_product_storage](@productno nvarchar(50),@storage int)
--WITH ENCRYPTION
as
begin
	update product set storage = @storage where productno = @productno
end
GO
/****** 对象:  StoredProcedure [dbo].[StoredProcedureconfig]    脚本日期: 04/09/2012 18:25:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[StoredProcedureconfig]
(
@tab nvarchar(500),    --表名
@total nvarchar(3000),    --条件,如果没有条件可以在前台写为“1=1”
@sort nvarchar(50),    --排序，如果没有排序则前台可以写为“ ”，注意中间的空格，这个是必须的
@kid nvarchar(1000)    --列名，需要查询的列，如果查询全部字段则可以写成 * 号
)
as
begin
set nocount on
declare 
@sql nvarchar(1000)
set @sql='select '+@kid+'  from '+@tab+' where '+@total+' '+@sort
EXEC (@sql)
end


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ActivityDetail_Get]    脚本日期: 04/09/2012 18:25:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas>
-- Create date: <2011-04-17>
-- Description:	<获取专题页明细>
-- Debug: exec XpProc_PdtRelateInfo_Get 437,-1
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ActivityDetail_Get]
@actid int --专题ID
AS
BEGIN
--获取专题信息
SELECT ActivityID,Title,Description,AD FROM Activity WHERE ActivityID=@actid
--获取专题分类
select ActCatID,CatName into #c from ActCat where ActivityID=@actid
select * from #c
--获取专题商品
select a.ActCatID,p.productid,p.productname,p.shortdesc,p.marketprice,p.memberprice,isnull(l.pmtprice,p.memberprice) as pmtprice,p.ImgFolder,p.ThumbnailImg,p.img5
from #c c(nolock),product p(nolock),ActCatProduct a(nolock)
left join PmtGoodsList l(nolock) on a.productid=l.productid
where c.actcatid=a.actcatid and a.productid=p.productid  and p.isforsale=1
order by a.sort
end


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Admin_Add]    脚本日期: 04/09/2012 18:25:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-09-17>
-- Description:	<添加管理员>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Admin_Add] 
@adminname varchar(50),--管理员账号
@password varchar(50),--管理员密码
@flag int=0,--标志：0普通管理员；3超级管理员
@realname varchar(50)='',--管理员真实姓名
@roleid int=-1,--所属角色ID
@status int=0,--状态
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
begin tran
if exists(select adminid from admin where adminname=@adminname)
begin
select @errorflag=1,@errormsg='该管理员账号已存在'
end
else
begin
insert into admin(adminname,password,flag,realname,roleid,status)values(@adminname,@password,@flag,@realname,@roleid,@status)
end
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Admin_Delete]    脚本日期: 04/09/2012 18:25:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-9-16>
-- Description:	<删除管理员>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Admin_Delete] 
@adminid int,--管理员ID
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
begin tran
declare @flag int
select @flag=flag from admin where adminid=@adminid
if @flag=3
begin
select @errorFlag=1,@errorMsg='不能删除超级管理员'
end
else
begin
delete from admin where adminid=@adminid
end
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Admin_Login]    脚本日期: 04/09/2012 18:25:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-09-17>
-- Description:	<管理员登录>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Admin_Login] 
@name varchar(20),--账号
@password varchar(20),--密码
@ip varchar(50),--登录者IP
@sessionid varchar(50),--登录者SESSIONID
@adminID int output,--管理员ID
@adminname varchar(20) output,--管理员账号
@realname varchar(20) output,--管理员真实姓名
@roleid int output,--角色ID
@flag int output,--管理员组
@status int output--管理员状态
AS
BEGIN
select @adminID=-1,@adminname='',@realname='',@roleid=-1,@flag=0,@status=-1
select @adminID=adminid,@adminname=adminname,@realname=realname,@roleid=roleid,@flag=flag,@status=Status from admin(nolock) where adminname=@name and [Password] = @password

if(@adminID>0)
begin
print('账号和密码验证通过')
select p.permission
from admin a(nolock),role r(nolock),rolepermission rp(nolock),permission p(nolock)
where a.adminid=@adminid and a.roleid=r.roleid and rp.roleid = r.roleid and rp.pid=p.pid

--更新登录次数和最后一次登录的时间
update admin set LastLogin = getdate(),LoginTimes = LoginTimes + 1 where AdminID=@adminID
--记录登录日志
exec XpProc_EventLog_Insert @adminid,@adminname,@realname,1,11,'登录',@ip
end

End


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Admin_Update]    脚本日期: 04/09/2012 18:25:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-09-17>
-- Description:	<更新管理员>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Admin_Update] 
@adminid int,--管理员ID
@adminname varchar(50),--管理员账号
@password varchar(50)=null,--管理员密码
@flag int=null,--标志：0普通管理员；3超级管理员
@realname varchar(50)='',--管理员真实姓名
@roleid int=-1,--所属角色ID
@status int=0,--状态
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
begin tran
update admin set adminname=@adminname,password=case when isnull(@password,'')='' then password else @password end,flag=case when isnull(@flag,-1)=-1 then flag else @flag end,realname=@realname,roleid=@roleid,status=@status where adminid=@adminid
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AdminDetail_Get]    脚本日期: 04/09/2012 18:25:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-09-17>
-- Description:	<获取管理员详细信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AdminDetail_Get]
@adminid int,
@adminname varchar(20) output,
@realname varchar(20) output,
@roleid int output,
@flag int output,
@status int output
AS
BEGIN
select @adminname='',@realname='',@roleid=-1,@flag=0,@status=-1
select @adminname=adminname,@realname=realname,@roleid=roleid,@flag=flag,@status=Status from admin(nolock) where AdminID=@adminid

select p.permission
from admin a(nolock),role r(nolock),rolepermission rp(nolock),permission p(nolock)
where a.adminid=@adminid and a.roleid=r.roleid and rp.roleid = r.roleid and rp.pid=p.pid
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AdminPassword_Update]    脚本日期: 04/09/2012 18:25:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-09-17>
-- Description:	<更新管理员密码>
-- =============================================
create PROCEDURE [dbo].[XpProc_AdminPassword_Update] 
@adminid int,--管理员ID
@oldpassword varchar(50)=null,--旧密码
@password varchar(50)=null,--新密码
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''
Begin Try
if exists (select adminid from admin where adminid=@adminid and password=@oldpassword)
begin
	update admin set password=@password where adminid=@adminid
end
else
begin
select @errorflag=1,@errormsg='密码验证不正确'
end
End Try

Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AdminPermission_Get]    脚本日期: 04/09/2012 18:25:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-09-15>
-- Description:	<获取用户权限>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AdminPermission_Get]
@adminid int
AS
BEGIN
select p.permission
from admin a(nolock),role r(nolock),rolepermission rp(nolock),permission p(nolock)
where a.adminid=@adminid and a.roleid=r.roleid and rp.roleid = r.roleid and rp.pid=p.pid
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AdvancePayment_Add]    脚本日期: 04/09/2012 18:25:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-09-09>
-- Description:	<预付款操作>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AdvancePayment_Add]
@memberid int=-1,--会员ID
@membername varchar(50),--会员账号
@money decimal(18,2),--充值金额
@flag int,--标志：-1扣除;1充值
@workpeople varchar(50),--操作人
@remark varchar(200),--备注
@errorflag int output,--错误标志
@errormsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
if @memberid=-1
select @memberid=memberid from member where [name]=@membername

if @memberid=-1
begin
select @errorflag=-1,@errormsg='不存在该会员'
return
end

--如果是扣减，传过来的金额又是正数的，要变成负数
if @flag=-1 and @money>0
select @money=-@money

begin tran
declare @balance decimal(18,2)
--更新会员的预付款
update member set AdvancePayment=AdvancePayment+@money where memberid=@memberid
select @balance=AdvancePayment from member where memberid=@memberid
--插入预付款操作日志
INSERT AdvancePayment(MemberID, AdvancePayment,Balance,Remark, WorkPeople)
VALUES (@memberid, @money,@balance,@remark, @workpeople)
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Agent_Add]    脚本日期: 04/09/2012 18:25:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-15>
-- Description:	<前台添加推广员或后台管理员增加推广员>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Agent_Add] 
@LevelID int,
@MemberID int,
@MemberName varchar(200),
@AgentName varchar(20),
@AgentPhone	varchar(20),
@AgentMobile varchar(20),
@AgentEmail	varchar(20)=null,
@AgentAddress varchar(100),
@AgentQQ varchar(20)=null,
@AgentMsn varchar(20)=null,
@IDCartNo varchar(50)=null,
@CompanyName varchar(100)=null,
@Postalcode	varchar(50)=null,
@SiteName varchar(20)=null,
@SiteUrl varchar(50)=null,
@SiteType varchar(20)=null,
@SiteAbstruct varchar(100)=null,
@BankName varchar(100)=null,
@AccountName varchar(100)=null,
@BankAccount varchar(50)=null,
@JumpUrl varchar(200)=null,
@AddTime datetime=null,
@AddUser int=null,
@AddUserName varchar(20)=null,
@UpdateUser	int=null,
@UpdateUserName	varchar(20)=null,
@UpdateTime	datetime=null,
@Auditor int=null,
@AuditorName varchar(20)=null,
@AuditTime datetime=null,
@Remark	varchar(50)=null,
@Status	int=null,
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
--select *from log order by addtime desc
select @memberid=memberid from member(nolock)where name=@membername

if isnull(@memberid,0)=0 
begin
select @errorflag=1,@errormsg='该会员不存在!'
end
else if exists(select levelid from agent(nolock) where memberid=@memberid)
begin
select @errorflag=1,@errormsg='该会员已申请过推广员!'
end
else
begin
--前台会员申请推广员时传过的@levelid=0,此时要从agentlevel表中取得最低的推广等级
--前台申请跟后台添加成功后的的提示是不同的，前台添加的还要审核，后台添加的就是已审核的
if isnull(@levelid,0)=0
begin
select top 1 @levelid=levelid from agentlevel(nolock) order by levelmoney asc
select @errorflag=0
select @errormsg='申请已提交，等待商城工作人员审核！'
end
else
begin
select @errorflag=0
select @errormsg='成功添加推广员！'
end
--向推广员表中插入记录
insert agent(
LevelID,
MemberID,
AgentName,
AgentPhone,
AgentMobile,
AgentEmail,
AgentAddress,
AgentQQ,
AgentMsn,
IDCartNo,
CompanyName,
Postalcode,
SiteName,
SiteUrl,
SiteType,
SiteAbstruct,
BankName,
AccountName,
BankAccount,
JumpUrl,
AddTime,
AddUser,
AddUserName,
UpdateUser,
UpdateUserName,
UpdateTime,
Auditor,
AuditorName,
AuditTime,
Remark,
Status
)
values(
@LevelID,
@MemberID,
@AgentName,
@AgentPhone,
@AgentMobile,
@AgentEmail,
@AgentAddress,
@AgentQQ,
@AgentMsn,
@IDCartNo,
@CompanyName,
@Postalcode,
@SiteName,
@SiteUrl,
@SiteType,
@SiteAbstruct,
@BankName,
@AccountName,
@BankAccount,
@JumpUrl,
getDate(),
@AddUser,
@AddUserName,
@UpdateUser,
@UpdateUserName,
@UpdateTime,
@Auditor,
@AuditorName,
@AuditTime,
@Remark,
@Status
)
end
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Agent_Delete]    脚本日期: 04/09/2012 18:25:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-29>
-- Description:	<删除推广员>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Agent_Delete] 
@AgentID int,
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg='成功删除推广员'
if exists(select agentid from agent where agentid=@agentid and agentname='admin')
begin
select @errorflag=1,@errormsg='不能删除推广员admin'
return
end
Begin Try
begin tran
--select @memberid=memberid from member(nolock)where name=@membername
--删除一个推广员后，要把这个推广员发展的会员的推广员设为'admin',所以推广员表中必须有admin推广员,且不能删除
update member set code='admin'  from agent where member.code=agent.agentname and agentid=@agentid
delete from agent where agentid=@agentid
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END









GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Agent_Get]    脚本日期: 04/09/2012 18:25:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-15>
-- Description:	<获得单个推广员或一组推广员>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Agent_Get] 
@agentID int=NULL,
@levelid int=null,--搜索条件
@type int=null,--按搜索条件 1是按会员名，2是按推广员
@keyword varchar(100)=null,--搜索关键字会员名或是按推广员
@errorFlag int=null output,--错误标志
@errorMsg varchar(200)=null output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''
Begin Try
--begin tran
if isnull(@agentid,0)<>0 --获得单个推广员等级信息
begin
SELECT a.*,m.name as MemberName from agent a(nolock),member m(nolock) where a.agentid=@agentid and a.memberid=m.memberid
select LevelName,LevelID from agentlevel(nolock) order by levelmoney
end
else --获得所有推广员列表
begin
--构造查询语句
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where=' m.memberid=a.memberid '
select @where=case @type when 1 then @where+' and name like '''+@keyword+'''' when 2 then @where+'  and agentname like '''+@keyword+'''' else @where end
if isnull(@levelid,0)<>0
select @where=@where+' and a.levelid='+cast(@levelid as varchar(10))
select @sqlstr='select a.*,m.name as MemberName from agent a(nolock),member m(nolock)where'+ @where
--insert log(content)values(@sqlstr)
exec (@sqlstr)
select LevelName,LevelID from agentlevel(nolock) order by levelmoney
end
--commit
End Try
Begin Catch
-- 捕捉错误
--rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Agent_LevelID_Update]    脚本日期: 04/09/2012 18:25:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-12-01>
-- Description:	<批量更新推广员的等级>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Agent_LevelID_Update] 
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
Begin Try
--得到推广员发展的会员购物总金额
select sum(productprice)as totalMoney,code into #t1 from agent a(nolock)
left join orders o(nolock) on o.code=a.agentname
group by code
--根据发展的会员的购物总金额，得到推广员可以获得的等级
select code,levelid,levelmoney into #t2 from agentlevel,#t1
where agentlevel.levelmoney<#t1.totalMoney
--从可用的多个级别中选择最高的一级
select t.* into #t3
from #t2 t
outer apply(select levelmoney=max(levelmoney) from #t2 where code=t.code) t2
where t.levelmoney=t2.levelmoney
--更新推广员的推广等级,因为后台加推广员时可以选择推广员的推广等级，如果获得的最高的等级小于当前的等级则不更新
update agent set levelid=#t3.levelid from  #t3,agentlevel
where agent.agentname=#t3.code 
and agent.levelid=agentlevel.levelid and agentlevel.levelmoney<#t3.levelmoney
select @errorflag=0
select @errormsg='更新成功！'
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Agent_Update]    脚本日期: 04/09/2012 18:25:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-15>
-- Description:	<前台添加推广员或后台管理员增加推广员>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Agent_Update]
@AgentID int,
@LevelID int,
@MemberID int,
@AgentName varchar(20),
@AgentPhone	varchar(20),
@AgentMobile varchar(20),
@AgentEmail	varchar(20)=null,
@AgentAddress varchar(100),
@AgentQQ varchar(20)=null,
@AgentMsn varchar(20)=null,
@IDCartNo varchar(50)=null,
@CompanyName varchar(100)=null,
@Postalcode	varchar(50)=null,
@SiteName varchar(20)=null,
@SiteUrl varchar(50)=null,
@SiteType varchar(20)=null,
@SiteAbstruct varchar(100)=null,
@BankName varchar(100)=null,
@AccountName varchar(100)=null,
@BankAccount varchar(50)=null,
@JumpUrl varchar(200)=null,
@AddTime datetime=null,
@AddUser int=null,
@AddUserName varchar(20)=null,
@UpdateUser	int=null,
@UpdateUserName	varchar(20)=null,
@UpdateTime	datetime=null,
@Auditor int=null,
@AuditorName varchar(20)=null,
@AuditTime datetime=null,
@Remark	varchar(50)=null,
@Status	int=null,
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=1,@errormsg=''
Begin Try
begin tran
--if exists(select levelid from agent where memberid=@memberid)
--begin
--select @errorflag=1,@errormsg='该会员已申请过推广员'
--end
--else
declare @oldstatus int
select @oldstatus= status from agent(nolock) where agentid=@agentid

if @oldstatus<>@status --改变了推广员的状态,要记录审核状态
begin
select @Auditor =@UpdateUser
select @AuditorName=@UpdateUserName
declare @oldstatusstr varchar(20)
declare @statusstr varchar(20)
select @oldstatusstr=case @oldstatus when -1 then '审核不通过' when 0 then '禁用' when 1 then '已审核' end
select @statusstr=case @status when -1 then '审核不通过' when 0 then '禁用' when 1 then '已审核' end
select @remark='状态由 '+@oldstatusstr+' 改为 '+@statusstr
end
begin
--向推广员表中插入记录
update agent set
LevelID=@LevelID,
--MemberID=@MemberID,
AgentName=@AgentName,
AgentPhone=@AgentPhone,
AgentMobile=@AgentMobile,
AgentEmail=@AgentEmail,
AgentAddress=@AgentAddress,
AgentQQ=@AgentQQ,
AgentMsn=@AgentMsn,
IDCartNo=@IDCartNo,
CompanyName=@CompanyName,
Postalcode=@Postalcode,
SiteName=@SiteName,
SiteUrl=@SiteUrl,
SiteType=@SiteType,
SiteAbstruct=@SiteAbstruct,
BankName=@BankName,
AccountName=@AccountName,
BankAccount=@BankAccount,
JumpUrl=@JumpUrl,
--AddTime,
--AddUser,
--AddUserName,
UpdateUser=@UpdateUser,
UpdateUserName=@UpdateUserName,
UpdateTime=getDate(),
Auditor=@Auditor,
AuditorName=@AuditorName,
AuditTime=getDate(),
Remark=@Remark,
Status=@Status
where agentid=@agentID
select @errorflag=0,@errormsg='修改成功！'
end
commit
End Try
Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentDrawing_Add]    脚本日期: 04/09/2012 18:25:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-24>
-- 推广员申请提现
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentDrawing_Add] 
@memberid int,
@DrawFinance decimal(18,2),
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorFlag=1
select @errorMsg=''

--判断申请的提现金额是否大于可提现的金额
if not exists (select finance from member where memberid=18 and finance>@drawfinance)
begin
select @errorFlag=1
select @errorMsg='申请提现金额大于可提取金额'
return
end

Begin Try
begin tran
insert AgentDrawing(
AgentID,
MemberID,
DrawFinance,
Status,
AppTime,
AddTime,
AddUser,
AddUserName
)
select a.agentid,m.memberid,@DrawFinance,0,getDate(),getDate(),m.memberid,name
from member m(nolock),agent a(nolock) where m.memberid=a.memberid and m.memberid=@memberid

select @errorFlag=0
select @errorMsg='提现申请已提交，等待处理'
commit tran
End Try
Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
End Catch
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentDrawing_Get]    脚本日期: 04/09/2012 18:25:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-25>
-- 后台查看推广员的申请提现
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentDrawing_Get] 
@type int=null,--查询条件，1按会员账号 2按推广员账号,其它值将会略过个这查询条件
@keyword varchar(100)=null,--查询关键字，推广员或会员账号
@begintime datetime=null,--查询提现申请开始时间
@endtime datetime=null,--查询提现申请结束时间
@status int =null,--提现状态，:0为待处理；1为已发放;-1为不发放,2为不限制
@errorflag int=null output,
@errormsg varchar(200)=null output
AS
BEGIN
set nocount on
Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' where ad.memberid=m.memberid and ad.agentid=a.agentid '
--构造查询条件
if isnull(@status,2)<>2
select @where=@where+' and ad.status='+cast(@status as varchar(2))

select @endtime=dateadd(day,1,@endtime)
if @begintime is not null and @endtime is not null
select @where =@where +' and apptime >='''+cast(@begintime as varchar(30)) +''' and apptime< '''+cast(@endtime as varchar(30))+''''
else if  @begintime is not null
select @where=@where+' and apptime>= '''+cast(@begintime as varchar(30))+''''
else if  @endtime is not null
select @where=@where+' and apptime< '''+cast(@endtime as varchar(30))+''''

select @where=case @type when 1 then @where+' and name = '''+@keyword+'''' when 2 then @where+' and agentname = '''+@keyword+'''' else @where end

select @sqlstr='
select DrawingID,name as membername,agentname,bankname,accountname,bankaccount,drawfinance,apptime,drawtime,ad.status 
from agentdrawing ad(nolock),member m(nolock),agent a(nolock)'+@where+' order by apptime desc'
insert log(content)values(@sqlstr)
Execute(@sqlstr)
End Try
Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END







GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentDrawing_Update]    脚本日期: 04/09/2012 18:25:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-25>
-- 更新提现状态
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentDrawing_Update] 
@drawingid int,
@status int =null,--提现状态，:0为待处理；1为已发放;-1为不发放
@ip varchar(50)=null,
@updateuser int=null,
@updateusername varchar(50)=null,
@errorflag int=null output,
@errormsg varchar(200)=null output
AS
BEGIN
set nocount on
Begin Try
begin tran
--发放后要更新member中的finance，否则不用更新member中的finance
--update member set finance=finance-drawfinance from agentdrawing where agentdrawing.memberid=member.memberid and agentdrawing.drawingid=@drawingid and @status=1
if @status=1
begin
update agentDrawing set status=@status,updateuser=@updateuser,updateusername=@updateusername,updatetime=getDate(),DrawTime=getDate() where drawingid=@drawingid
--发放提现要写日志
declare @MemberID int,@Mobile varchar(20),@Finance decimal(18, 2),@AddIP varchar(50),@AddUser int,@AddUserName varchar(50)	
select @memberid=ad.memberid,@mobile=mobile,@Finance=drawFinance from member m(nolock),agentdrawing ad(nolock)
where m.memberid=ad.memberid and ad.drawingid=@drawingid 
exec XpProc_XpFinanceLog_Insert @MemberID,@Mobile,@Finance,-1,null,null,null,'发放会员申请的提现',null,
'发放会员申请的提现','发放会员申请的提现',@AddIP,null,null,@updateuser,@updateusername
end
else
begin
update agentDrawing set status=@status,updateuser=@updateuser,updateusername=@updateusername,updatetime=getDate()where drawingid=@drawingid
end
--exec XpProc_FinanceLog_Insert
--@MemberID,@Mobile,@Finance,@Flag,@NeedSend,@IsSended,@SendTime,@FinanceType,@FromID,@FromRemark,@Remark,@AddIP,@GenerateTime,
--@AddTime,@AddUser,@AddUserName
select @errorflag=0
select @errormsg='更新成功'
commit
End Try
Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentDrawingRelateInfo_Get]    脚本日期: 04/09/2012 18:25:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-24>
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentDrawingRelateInfo_Get] 
@issue varchar(50)=null,--查询条件，期数
@memberid varchar(20),
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@finance decimal(18,2) output, --会员的总的推广提成金额
@candrawing decimal(18,2) output,--会员可以申请的提成金额
@frozen decimal(18,3) output,--会员申请的还没有审批的提成金额
@totalpage int output,--总页数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
--declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0
Begin Try

select @finance=m.finance,@candrawing=(m.finance-sum(case when ad.status=0 then drawfinance else 0 end)),@frozen=sum(case when ad.status=0 then drawfinance else 0 end)
from member m(nolock) left join agentdrawing ad(nolock)
on m.memberid=ad.memberid 
where m.memberid=@memberid
group by m.finance

declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' ad.memberid='+cast(@memberid as varchar(10))
if isnull(@issue,'')<>''
select @where=@where+' and issue='+@issue

select @sqlstr='select *from(
select DrawingID, DrawFinance,AppTime,case status when 0 then ''未处理'' when -1 then ''已取消'' when 1 then ''已处理'' end as status,DrawTime,Row_number() over(order by apptime desc) as rowno 
from agentdrawing ad(nolock)
where ' + @where + ') as ma where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
Execute(@sqlstr)

--获取总记录数和总页数
declare @totalcount int 
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by apptime desc) as rowno from agentdrawing ad(nolock)
where ' + @where + ') as p)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentFinance_Add]    脚本日期: 04/09/2012 18:25:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-19>
-- Description:	已付款的先款后货的订单和已确认的先货后款订单,根据订单明细及AgentCatRatio表计算提成，插入AgentFinance表，status=0；订单状态改变时同步判断更新结算状态；结算时，筛选出status=2的记录进行结算。
-- 提交结算后，结算状态Status变为4，结算时间PayTime为当前时间，金额Finance累加到会员的推广电子账户Finance字段，生成期数写入Issue
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentFinance_Add] 
@orderid int,
@errorFlag int=null output,--错误标志
@errorMsg varchar(200)=null output--错误信息
AS
BEGIN
select @errorFlag=1
select @errorMsg=''
Begin Try
begin
--向推广员表中插入记录
--根据订单明细及AgentCatRatio表计算提成
--连接四张表，得到商品的一级分类编号，订单商品的价格，推广员的等级
select orderid,orderno,ordertime,subprice as orderprice,m2.memberid,left(c.categoryno,4)as categoryno,m1.code,a.levelid ,a.agentid into #t1 from orderproduct op(nolock)
left join category c(nolock) on op.categoryid=c.categoryid
left join member m1(nolock) on op.memberid=m1.memberid
left join member m2(nolock)on m1.code=m2.name --如果Member 没有code 就不用处理了就返回一个空的#t1
--join agent a(nolock) on a.agentid=m.agentid --如果Member 没有agentID 就不用处理了就返回一个空的#t1
--join agent a(nolock) on a.agentName=m.code --如果Member 没有code 就不用处理了就返回一个空的#t1
join agent a(nolock) on a.memberid=m2.memberid 
where op.orderid=@orderid and a.status=1

--#t跟agnetcatratio表连接，得到根据推广员的等级，计算出一个订单中每个商品推广提成金额
select #t1.*,orderprice*isnull(ratio,0) as finance into #t2 from #t1 left join agentcatratio acr on #t1.categoryno=acr.categoryno and acr.levelid=#t1.levelid
--合并一个订单总的提成，因为一个订单可能会购买几个商品，每个商品对应一个提成金额
declare @finance decimal(18,2),@orderprice decimal(18,2)
select @finance=sum(finance),@orderprice=sum(orderprice) from #t2 group by orderid

--向财务统计表中插入一个订单对应的推广提成
insert AgentFinance(
OrderID,
OrderNo,
OrderTime,
OrderPrice,
AgentID,
MemberID,
Finance,
Issue,
Remark,
Status,
AddTime,
PayTime,
AddUser,
AddUserName,
UpdateUser,
UpdateUserName,
UpdateTime,
Auditor,
AuditorName,
AuditTime
)
select top 1 orderid,OrderNo,OrderTime,@OrderPrice,AgentID,Memberid,@finance,'','',0,getDate(),null,null,null,null,null,null,null,null,null
from #t2 
end
select @errorFlag=0
select @errorMsg='添加成功'
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END













GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentFinance_Get]    脚本日期: 04/09/2012 18:25:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-20>
-- Description:	按条件查询出AgentFinance
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentFinance_Get] 
--@keyword varchar(100)='',  --关键字
--@keysql varchar(1000)=null,
@begintime datetime=null,
@endtime datetime=null,
--@sort varchar(50)=null,
@status int=null,
--@pagesize int=10,--每页显示商品数
--@pageno int=1,--页码	
--@totalpage int=NULL output,--总页数
@totalcount int =NULL output,--总记录数
@totalAgent int=null output,--这期要结算的推广员数量
@totalFinance decimal(18,2)=null output,--这期要结算的总金额
@errorFlag int=NULL output,--错误标志
@errorMsg varchar(200)=NULL output--错误信息
AS
BEGIN
select @errorFlag=1
select @errorMsg=''

Begin Try
begin
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where=' 1=1 and status='+cast(isnull(@status,2) as varchar(1))

if @endtime is not null
begin
select @endtime=dateadd(day,1,@endtime)
end
if @begintime is not null and @endtime is not null
select @where =@where +' and AddTime >='''+cast(@begintime as varchar(30)) +''' and AddTime< '''+cast(@endtime as varchar(30))+''''
else if  @begintime is not null
select @where=@where+' and AddTime>= '''+cast(@begintime as varchar(30))+''''
else if  @endtime is not null
select @where=@where+' and AddTime< '''+cast(@endtime as varchar(30))+''''

create table #t1(agentid int,finance decimal(18,2))
--select *from agentFinance
select @sqlstr='insert into #t1 select agentid ,sum(finance) as finance from agentFinance(nolock) where '+@where+' group by agentid'
insert log(content)values(@sqlstr)
exec (@sqlstr)
select agentid ,finance into #t2 from agentFinance where status=2 order by agentid
--计算这期要结算的推广员总数，跟推广的提成总金额
select @totalagent=count(agentid),@totalfinance=sum(finance) from #t1
--每个推广员这一期可结算总金额
select #t1.*,AgentName,name,levelname,a.memberid from #t1 left join agent a(nolock) on #t1.agentid=a.agentid 
left join member m(nolock)
--on a.memberid=m.memberid
on a.memberid=m.memberid
left join agentlevel  al(nolock)
on a.levelid=al.levelid
----推广员从每订单获得的提成金额
--select #t2.*,AgentName,name,levelname,a.memberid from #t2 left join agent a(nolock) on #t2.agentid=a.agentid 
--left join member m(nolock)
--on a.memberid=m.memberid
--left join agentlevel  al(nolock)
--on a.levelid=al.levelid
select @totalcount=isnull(@totalcount,0)
end
select @errorFlag=0
select @errorMsg='操作成功!'
End Try

Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END
















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentFinance_Status_Update]    脚本日期: 04/09/2012 18:25:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-19>
-- Description 更新当更新订单的状态时，也要同步更新AgentFinance的结款状态。
-- AgentFinance的结款状态。-1：无须结款；0：不可结款；1：未结款；2：待结款；3：结款中；4：已结款
-- 当先款后货的订单客户付款后或货到付款的订单经过确认后，如果这个客户有推广员的话要向AgentFinance表中写入一条记录，记录这个推广员所得到的提成金额，但此时这个金额是不能提现的，因为此刻这个
-- 订单还没有还没有完成，客户有可能要求取消订单。
-- 当订单取消时，把AgentFinance的状态置为-1，说明这个推广提成金额是无效的了。
-- status=1的状态暂时没有用到
-- 当订单的状态为完成时，把AgentFinance的状态置为2，表示这个提成金额是可以更新到推广员的账户中去的
-- 当把推广提成更新到推广员的账号后，为AgentFinance的状态置为4，表示这个推广提成已处理了。
-- 暂时不处理订单的退换货返修时AgentFinance
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentFinance_Status_Update] 
@orderid int,
@errorFlag int =null output,--错误标志
@errorMsg varchar(200)=null output--错误信息
AS
BEGIN
select @errorFlag=1
select @errorMsg=''
Begin Try
begin
declare @status int 
select @status=status from orders(nolock) where orderid=@orderid
if @status=12 --订单完成
update AgentFinance set status=2 WHERE ORDERID=@orderid and status=0
else if @status=10 --订单取消
update AgentFinance set status=-1 WHERE ORDERID=@orderid
else if @status=11 --失败
update AgentFinance set status=-1 WHERE ORDERID=@orderid
--update AgentFinance set status=4 ,paytime=getDate(),issue=CONVERT(varchar(8),getdate(),112 ) WHERE ORDERID=@orderid

end
select @errorFlag=0
select @errorMsg='添加成功'
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END










GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentFinanceRelateInfo_Get]    脚本日期: 04/09/2012 18:25:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-12-09>
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentFinanceRelateInfo_Get] 
@issue varchar(50)=null,--查询条件，期数
@memberid varchar(20),
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@status int=null,--agentFinance的状态，-1，0， 2，4几种状态
@finance decimal(18,2) output, --会员的总的推广提成金额
@candrawing decimal(18,2) output,--会员可以申请的提成金额
@frozen decimal(18,3) output,--会员申请的还没有审批的提成金额
@totalpage int output,--总页数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
--declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0
Begin Try

select @finance=m.finance,@candrawing=(m.finance-sum(case when ad.status=0 then drawfinance else 0 end)),@frozen=sum(case when ad.status=0 then drawfinance else 0 end)
from member m(nolock),agentdrawing ad(nolock)
where m.memberid=ad.memberid and m.memberid=@memberid
group by m.finance

--分页查询开始
declare @sqlstr nvarchar(4000),@where nvarchar(4000),@totalcount int 
--status<4是查找没有结款的推广提成，从agetfinance中得到记录
if @status<4
begin
select @where = ' o.memberid=m.memberid and af.memberid='+cast(@memberid as varchar(10))+' and af.status='+cast(@status as varchar(2))+' and af.orderid=o.orderid'
if isnull(@issue,'')<>''
select @where=@where+' and issue='+@issue

select @sqlstr='select *from(
select fid, case issue when '''' then ''----'' else issue end as issue, af.Finance,isnull(convert(varchar(10),af.paytime,120),''----'') as paytime,
af.orderno,m.name,o.ordertime,o.productprice,
Row_number() over(order by fid desc) as rowno 
from agentFinance af(nolock),member m(nolock),orders o(nolock)
where ' + @where + ') as am where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
--insert log(content)values(@sqlstr)
Execute(@sqlstr)
--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by fid desc) as rowno from agentfinance af(nolock),member m(nolock),orders o(nolock)
where ' + @where + ') as p)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output
end
--查找已结款的推广提成，从agentpay中得到记录
else if @status=4 
begin
select @where = ' ap.memberid=m.memberid and m.memberid='+cast(@memberid as varchar(10))
if isnull(@issue,'')<>''
select @where=@where+' and issue='+@issue
select @sqlstr='select *from(
select agentpayid as fid, issue , ap.Finance,paytime,Row_number() over(order by agentpayid desc) as rowno 
from agentPay ap(nolock),member m(nolock)
where ' + @where + ') as am where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
insert log(content)values(@sqlstr)
Execute(@sqlstr)
--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by agentpayid desc) as rowno from agentpay ap(nolock),member m(nolock)
where ' + @where + ') as p)'
--insert log(content)values(@sqlstr)

--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output
end
--分布查询结束
--计算总页数
if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentLevel_Add]    脚本日期: 04/09/2012 18:25:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-14>
-- Description:	<添加推广员等级>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentLevel_Add] 
@LevelName	varchar(100),
@levelMoney	decimal(18,2),
@AddUser	int	,
@AddUserName varchar(20),
@AddTime	datetime=null,
@UpdateUser	int =null,
@UpdateUserName	varchar(20)=null,
@UpdateTime	datetime=null,
@Auditor	int=null,
@AuditorName	varchar(20)=null,
@AuditTime	datetime=null,
@CategoryIDs varchar(8000),
@CatRatios varchar(8000),
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''
--insert log(content)values(@CategoryIDs)
--insert log(content)values(@CatRatios)
if exists(select levelid from agentLevel where levelname=@levelname)
begin
select @errorflag=1,@errormsg='该推广员等级名称已存在'
return 
end
Begin Try
begin tran
begin
--向推广员等级表中插入记录
insert into agentlevel(LevelName,LevelMoney,AddUser,AddUserName,AddTime,UpdateUser,UpdateUserName,UpdateTime,Auditor,AuditorName,AuditTime)
values(@LevelName,@levelMoney,@AddUser,@AddUserName,getDate(),@UpdateUser,@UpdateUserName,@UpdateTime,@Auditor,@AuditorName,@AuditTime)
declare @levelID int 
set @levelID =@@identity
--向推广商品分类提成比例表中插入各个分类的提成比例
select id,value as CategoryID into #t1 from SplitToTable_Func(@CategoryIDs,',')
select id,value as CatRatio into #t2 from SplitToTable_Func(@CatRatios,',')
insert into AgentCatRatio(LevelID,CategoryID,CategoryNo,Ratio,AddUser,AddUserName,AddTime,UpdateUser,UpdateUserName,UpdateTime,Auditor,AuditorName,AuditTime)
select @LevelID,#t1.CategoryID,CategoryNo,CatRatio,@AddUser,@AddUserName,getDate(),@UpdateUser,@UpdateUserName,@UpdateTime,@Auditor,@AuditorName,@AuditTime
from #t1,#t2,category c (nolock)where #t1.id=#t2.id and #t1.CategoryID=c.CategoryID
end
select @errorflag=0
select @errormsg='添加成功！'
commit
End Try
Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentLevel_Delete]    脚本日期: 04/09/2012 18:26:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-14>
-- Description:	<删除推广员等级>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentLevel_Delete] 
@LevelID int,
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
--insert log(content)values(@levelid)
--select *from log order by addtime desc
select @errorflag=0,@errormsg='删除成功'
--推广员等级已有推广员，所以不能删除
if exists(select levelid from agent(nolock)where levelid=@levelid)
begin
	select @errorflag=1
	select @errormsg='这个推广等级已有推广员，不能删除'
	return 
end
Begin Try
begin tran
delete from AgentLevel where LevelID=@LevelID
delete from AgentCatRatio where LevelID=@LevelID
commit
End Try
Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentLevel_Get]    脚本日期: 04/09/2012 18:26:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-15>
-- Description:	<获得单个推广员等级或一组推广员等级>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentLevel_Get] 
@LevelID int=NULL,
@errorFlag int=null output,--错误标志
@errorMsg varchar(200)=null output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''
--insert log(content)values(@levelid)
Begin Try
begin tran
if isnull(@LevelID,0)<>0 --获得单个推广员等级信息
begin
SELECT c.categoryid,c.categoryno,c.name, levelname,levelmoney,isnull(cast(ratio as varchar(20)),'')as Ratio FROM AgentLevel al(nolock)left join AgentcatRatio acr(nolock) on al.levelid=acr.levelid 
right join category c(nolock) on acr.categoryid=c.categoryid and acr.levelid=@LevelID
where c.parentno=1
end
else --获得所有推广员等级列表
begin
select *from  agentlevel (nolock) order by levelmoney
select *from agentcatratio a(nolock),category c(nolock)where a.categoryid=c.categoryid
end
commit
End Try
Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END








GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentLevel_Update]    脚本日期: 04/09/2012 18:26:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-15>
-- Description:	<修改推广员等级>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentLevel_Update] 
@LevelID int,
@LevelName	varchar(100),
@LevelMoney	decimal(18,2),
@AddUser int=null,
@AddUserName varchar(20)=null,
@AddTime datetime=null,
@UpdateUser	int =null,
@UpdateUserName	varchar(20)=null,
@UpdateTime	datetime=null,
@Auditor int=null,
@AuditorName varchar(20)=null,
@AuditTime datetime=null,
@CategoryIDs varchar(8000),
@CatRatios varchar(8000),
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=1,@errormsg=''

Begin Try
begin tran
if exists(select levelid from agentLevel where levelname=@levelname and levelid<>@levelid)
begin
select @errorflag=1,@errormsg='该推广员等级已存在！'
end
else
begin
--更新推广员等级表中记录
update agentlevel set LevelName=@LevelName,LevelMoney=@LevelMoney,UpdateUser=@updateUser,UpdateUserName=@UpdateUserName,UpdateTime=getDate()
where levelid=@levelid

--更新推广商品分类提成比例表中各个分类的提成比例
select id,value as CategoryID into #t1 from SplitToTable_Func(@CategoryIDs,',')
select id,value as CatRatio into #t2 from SplitToTable_Func(@CatRatios,',')

--categoryid 已存在的话，就更新，不存在就插入新记录
update AgentCatRatio set Ratio=CatRatio,UpdateUser=@updateuser,UpdateUserName=@updateusername,UpdateTime=getDate()
from #t1,#t2,AGENTCATRATIO a (nolock)where #t1.id=#t2.id and #t1.CategoryID=a.CategoryID and a.levelid=@levelid

insert into AgentCatRatio(LevelID,CategoryID,CategoryNo,Ratio,AddUser,AddUserName,AddTime,UpdateUser,UpdateUserName,UpdateTime,Auditor,AuditorName,AuditTime)
select @LevelID,t1.CategoryID,c.CategoryNo,catRatio,@UpdateUser,@UpdateUserName,getDate(),null,null,@UpdateTime,@Auditor,@AuditorName,@AuditTime
from #t1 t1 left join #t2 t2 on t1.id=t2.id 
left join category c(nolock) on t1.CategoryID=c.CategoryID 
left join agentCatRatio a(nolock) on t1.Categoryid= a.CategoryID and a.levelid=@LevelID
where a.categoryid is null
select @errorflag=0
select @errormsg='更新成功！'

end
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentMember_Get]    脚本日期: 04/09/2012 18:26:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-24>
-- Description:	<会员中心,推广员得到发展的会员>
-- Debug:
/*
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentMember_Get]
@memberid int, --会员ID
@key varchar(100)=null,--关键字
@pagesize int=null,--每页显示数
@pageno int=1,--页码
@totalpage int output,--总页数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
--declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0
Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
--select @where=' a.memberid='+cast(@memberid as varchar(10))+' and m.agentid=a.agentid ' 
select @where=' m1.code=m2.name and m2.memberid= '+cast(@memberid as varchar(10))
if isnull(@key,'')<>''
select @where=@where+' and OrderNo like ''%' + @key + '%'''

--这个是会员中心以分页的方式得到发展的会员
if isnull(@pagesize,0)<>0
begin
select @sqlstr='select *from(
select m1.MemberID, m1.Name,m1.AddDate,m1.Expenditure,m1.Spending,Row_number() over(order by m1.AddDate desc) as rowno 
from member m1(nolock),member m2(nolock)
where ' + @where + ') as ma where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
--insert log (content)values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数
declare @totalcount int 
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by m1.AddDate desc) as rowno from member m1(nolock),member m2(nolock) where ' + @where + ') as p)'
--print @sqlstr

Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)
end
else--管理后台查看发展的会员
begin
select @sqlstr='select *from(
select m1.MemberID, m1.Name,m1.AddDate,m1.Expenditure,m1.Spending,Row_number() over(order by m1.AddDate desc) as rowno 
from member m1(nolock),member m2(nolock)
where ' + @where + ') as member'
insert log(content)values(@sqlstr)
Execute(@sqlstr)
end
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END







GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentPay_Add]    脚本日期: 04/09/2012 18:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-19>
-- Description:	结算提成后，AgentFinance中status=2 的置为4 。并向AgentPay表中插入推广员这一期的总的提成金额，并更新Member表中的Finance
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentPay_Add] 
--@fids varchar(8000),
@agentIDs varchar(8000),
@adduser int,
@addusername varchar(20),
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorFlag=1
select @errorMsg=''
Begin Try
begin tran
begin
select id,value as agentid into #t from SplitToTable_Func(@agentids,',')
select id,fid into #t1 from agentfinance af(nolock),#t where af.agentid=#t.agentid and status=2

--select fid into #t1 from agentfinance af(nolock)where status=2
--结算日期
declare @issue varchar(50)
select @issue=CONVERT(varchar(8),getdate(),112 )
--按AgentID分组，取出Status=2的记录，计算每个推广员一期的总的提成金额
select af.agentid,sum(finance)as finance,a.memberid into #t2 
from agentfinance af(nolock) join #t1 on af.fid=#t1.fid
left join agent a(nolock) on af.agentid= a.agentid
where af.status=2 group by af.agentid,a.memberid
--AgentFinance中status=2 的置为4,期数为当前的日期
update agentFinance set status=4,issue=@issue ,paytime=getDate() from agentFinance af(nolock),#t1 where af.fid=#t1.fid and status=2

--因为可以一次处理多个推广员的结算，这里用游标来处理
declare @agentid int,@finance decimal(18,2),@memberid int
declare agentid_items_cursor cursor for
select agentid,finance,memberid from #t2 order by agentid desc
open agentid_items_cursor
fetch next from agentid_items_cursor into
@agentid,@finance,@memberid
while @@fetch_status=0
begin
--所以如果在AgentPay表存在AgentPay.AgentID=#t2.AgentID且Issue=这个结算期数，那就只能更新AgentID这期的提成金额
declare @remark varchar(50)--写日志用到
if exists (select agentpayid from agentpay where AgentID=@agentID AND issue=@issue)
begin
update AgentPay set Finance=Finance+ @finance,Updatetime=getDate(),updateuser=@adduser,updateusername=@addusername where AgentID=AgentID AND issue=@issue 
set @remark='更新了第 '+cast(@issue as varchar(10))+' 期财务结算'
end
else
begin
insert AgentPay(AgentID,MemberID,Finance,Issue,PayTime,AddTime,AddUser,AddUserName,
UpdateUser,UpdateUserName,UpdateTime,Auditor,AuditorName,AuditTime
)values(@agentid,@memberid,@finance,@issue,getDate(),getDate(),@adduser,@addusername,null,null,null,null,null,null)
set @remark='第 '+cast(@issue as varchar(10))+' 期财务结算'
end
--更新member表中的finance
declare @prefinance decimal(18,2)
declare @newfinance decimal(18,2)
select @prefinance=isnull(finance,0) ,@newfinance=isnull(finance,0)+@finance
from member (nolock) where memberid=@memberid
update member set finance=@newfinance where memberid=@memberid
----写入积分日志
INSERT xpfinancelog(
MemberID, Mobile,Prefinance,finance,Totalfinance, Flag, NeedSend, IsSended, SendTime,financeType, FromID, 
FromRemark, Remark, AddIP, GenerateTime, AddTime, AddUser, AddUserName
)
values(@memberid,null,@prefinance,@finance,@newfinance,1,null,null,null,@remark,'',@remark,@remark,null,getDate(),getDate(),@adduser,@addusername)
fetch next from agentid_items_cursor into @agentid,@finance,@memberid
end                                           
close agentid_items_cursor   
deallocate agentid_items_cursor

--因为有可能会分几次提交财务结算
----所以如果在AgentPay表存在AgentPay.AgentID=#t2.AgentID且Issue=这个结算期数，那就只能更新AgentID这期的提成金额
--declare @remark varchar(50)--写日志用到
--if exists (select agentpayid from agentpay,#t2 where AgentPay.AgentID=#t2.AgentID AND issue=@issue)
--begin
--update AgentPay set AgentPay.Finance=AgentPay.Finance+ #t2.Finance,Updatetime=getDate(),updateuser=@adduser,updateusername=@addusername from AgentPay (nolock),#t2 where AgentPay.AgentID=#t2.AgentID AND issue=@issue 
--set @remark='更新了第 '+cast(@issue as varchar(10))+' 期财务结算'
--end
--else--否则 AgentPay表不存在AgentPay.AgentID=#t2.AgentID且Issue=这个结算期数，AgentPay中插入每个推广员一期对应的总的提成金额
--begin
--insert AgentPay(
--AgentID,
--MemberID,
--Finance,
--Issue,
--PayTime,
--AddTime,
--AddUser,
--AddUserName,
--UpdateUser,
--UpdateUserName,
--UpdateTime,
--Auditor,
--AuditorName,
--AuditTime
--)
--select top 1 #t2.agentid,#t2.memberid,#t2.finance,@issue,getDate(),getDate(),@adduser,@addusername,null,null,null,null,null,null 
--from #t2 left join AgentPay
--on AgentPay.Agentid=#t2.Agentid
--set @remark='第 '+cast(@issue as varchar(10))+' 期财务结算'
--end
----更新member表中的finance
--select isnull(m.finance,0) as prefinance,isnull(m.finance,0)+#t2.finance as newfinance,#t2.memberid,#t2.finance as finance,mobile into #t4
--from member m(nolock),#t2 where m.memberid=#t2.memberid
--update member set member.finance=isnull(member.finance,0)+ #t2.finance from member (nolock),#t2 where member.memberid=#t2.memberid
----写入积分日志
--INSERT xpfinancelog(
--MemberID, Mobile,Prefinance,finance,Totalfinance, Flag, NeedSend, IsSended, SendTime,financeType, FromID, 
--FromRemark, Remark, AddIP, GenerateTime, AddTime, AddUser, AddUserName
--)
--select memberid,mobile,prefinance,finance,newfinance,1,null,null,null,@remark,'',@remark,@remark,null,getDate(),getDate(),@adduser,@addusername
--from #t4
----@MemberID, @Mobile,@prefinance,@finance,@newfinance,@Flag, COALESCE(@NeedSend, (1)), COALESCE(@IsSended, (0)), @SendTime, @financeType, @FromID, 
----@FromRemark, @Remark, @AddIP, COALESCE(@GenerateTime, getdate()), COALESCE(@AddTime, getdate()), COALESCE(@AddUser, -1), COALESCE(@AddUserName,'system')
----)
end
select @errorFlag=0
select @errorMsg='结算成功'
commit tran
End Try
Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentPay_Get]    脚本日期: 04/09/2012 18:26:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-21>
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentPay_Get] 
@issue varchar(50),--查询条件，期数
@agentname varchar(20),--查询条件，推广员名称
@errorflag int=null output,
@errormsg varchar(200)=null output
AS
BEGIN
set nocount on
Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' ap.agentid=a.agentid and a.memberid=m.memberid '
if isnull(@issue,'')<>''
select @where=@where+' and issue='+@issue


if isnull(@agentname,'')<>''
select @where=@where+' and agentname='''+@agentname+''''

select @sqlstr='select a.Agentid,Issue,PayTime,agentpayid,agentname,name, ap.finance from agentpay ap(nolock),agent a(nolock),member m(nolock) where '+@where+ ' order by paytime desc'

Execute(@sqlstr)
select distinct(issue) from agentpay ap(nolock) order by issue desc

End Try
Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentPayDetail_Get]    脚本日期: 04/09/2012 18:26:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-21>
-- Description:	会员中心,推广员查看他的推广提成结算的金额,及相应的明细
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentPayDetail_Get] 
@agentpayid int,--查询条件，期数
@memberid int,--会员ID
@pagesize int=10,--每页显示数量
@pageno int=1,--页码
@finance decimal(18,2) output,
@issue varchar(50) output,
@totalpage int output,--总页数
@errorflag int=null output,
@errormsg varchar(200)=null output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
select @finance=finance,@issue=issue from agentpay(nolock) where AgentPayID=@agentpayid and memberid= @memberid
select * from(
select fid,Agentid,Issue,PayTime,name,af.finance,ordertime,orderno,orderprice,Row_number() over(order by fid desc) as rowno from agentfinance af(nolock),member m(nolock) where af.memberid=m.memberid and @issue=issue and af.memberid=@memberid
)as m 
where rowno> @pagesize*@pageno and rowno<=@pagesize*(@pageno+1)

declare @totalcount int
select @totalcount=max(rowno)from(
select Row_number() over(order by fid desc) as rowno 
from agentfinance af(nolock),member m(nolock)
where af.memberid=m.memberid and @issue=issue and af.memberid=@memberid)as temp

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)

End Try
Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentPayRelateInfo_Get]    脚本日期: 04/09/2012 18:26:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-21>
-- Description:	
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentPayRelateInfo_Get] 
@issue varchar(50)=null,--查询条件，期数
@memberid varchar(20),
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@finance decimal(18,2) output, --会员的总的推广提成金额
@candrawing decimal(18,2) output,--会员可以申请的提成金额
@frozen decimal(18,3) output,--会员申请的还没有审批的提成金额
@totalpage int output,--总页数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
--declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0
Begin Try

select @finance=m.finance,@candrawing=(m.finance-sum(case when ad.status=0 then drawfinance else 0 end)),@frozen=sum(case when ad.status=0 then drawfinance else 0 end)
from member m(nolock),agentdrawing ad(nolock)
where m.memberid=ad.memberid and m.memberid=@memberid
group by m.finance

declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' ap.memberid=m.memberid and m.memberid='+cast(@memberid as varchar(10))
if isnull(@issue,'')<>''
select @where=@where+' and issue='+@issue

select @sqlstr='select *from(
select AgentPayID, Issue, ap.Finance,PayTime,Row_number() over(order by PayTime desc) as rowno 
from agentpay ap(nolock),member m(nolock)
where ' + @where + ') as ma where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

Execute(@sqlstr)

--获取总记录数和总页数
declare @totalcount int 
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by PayTime desc) as rowno from agentpay ap(nolock),member m(nolock)
where ' + @where + ') as p)'
--print @sqlstr

Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AgentRelateInfo_Get]    脚本日期: 04/09/2012 18:26:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-21>
-- Description:	会员中心MyAgent页面，返回推广员的一些统计信息
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AgentRelateInfo_Get] 
@memberid int,
@begintime datetime=null,--查询条件开始时间
@endtime datetime=null,--查询条件结束时间
@membername varchar(200)=null,--查询条件，下订的会员名
@pagesize int=10,
@pageno int=0,
@agentid int =null output,
@name varchar(400)=null output,
@jumpurl varchar(200)=null output,
@totalMembers int=null output,
@totalpage int output,--总页数
@errorflag int=null output,
@errormsg varchar(200)=null output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0
Begin Try

select @agentid=agentid,@jumpurl=jumpurl,@name=name from agent(nolock),member(nolock) where agent.memberid=member.memberid and member.memberid=@memberid
--已发展会员总数
--select @totalMembers=count(memberid)from member(nolock) where agentid=@agentid
select @totalMembers=count(memberid) from member(nolock) where code=@name

--这个推广员发展的会员的订单总数
select orderid,ordertime,orderno,Productprice,o.status,paytype,PaymentType,name as membername,
case
--先款后货
when o.status=0 and paytype<5 then '未付款' 
when o.status=1 and paytype<5 then '部分付款'
when o.status=2 and paytype<5 then '已付款' 
when o.status=3 and paytype<5 then '已确认'
when o.status=4 and paytype<5 then '正在配货' 
when o.status=5 and paytype<5 then '部分发货'
when o.status=6 and paytype<5 then '已发货' 
when o.status=7 and paytype<5 then '已签收'
when o.status=8 and paytype<5 then '等待退款' 
when o.status=9 and paytype<5 then '已退款'
when o.status=10 and paytype<5 then '交易取消' 
when o.status=11 and paytype<5 then '交易失败'
when o.status=12 and paytype<5 then '交易完成'
--货到付款
when o.status in(0,1,2) and paytype>=5 then '未确认' 
when o.status=3 and paytype>=5 then '已确认'
when o.status=4 and paytype>=5 then '正在配货' 
when o.status=5 and paytype>=5 then '部分发货'
when o.status=6 and paytype>=5 then '已发货' 
when o.status=7 and paytype>=5 then '已签收'
when o.status=8 and paytype>=5 then '等待退款' 
when o.status=9 and paytype>=5 then '已退款'
when o.status=10 and paytype>=5 then '交易取消' 
when o.status=11 and paytype>=5 then '交易失败'
when o.status=12 and paytype>=5 then '交易完成'
end as orderstatus
into #t from orders o(nolock),member m(nolock) where o.code=m.name and m.memberid=@memberid

--上个月的订单总数,及已付款订单个数，已完成订单个数，已完成订单总金额
select count(orderid)as totalOrders,
isnull(sum(case when (status=2 and paytype<5)or (status=3 and paytype>=5) then 1 else  0 end),0) as paiedorders,
isnull(sum(case when status=12 then 1 else  0 end),0) as finishOrders,
isnull(sum(case when status=12 then productprice else  0 end),0) as totalprices
from #t where datediff(month ,ordertime,getDate())=1

--这个月的订单总数,及已付款订单个数，已完成订单个数，已完成订单总金额
select count(orderid)as totalOrders,
isnull(sum(case when (status=2 and paytype<5)or (status=3 and paytype>=5) then 1 else  0 end),0) as paiedorders,
isnull(sum(case when status=12 then 1 else  0 end),0) as finishOrders,
isnull(sum(case when status=12 then productprice else  0 end),0) as totalprices
from #t where datediff(month ,ordertime,getDate())=0

--订单总数,及已付款订单个数，已完成订单个数，已完成订单总金额
select count(orderid)as totalOrders, 
isnull(sum(case when (status=2 and paytype<5)or (status=3 and paytype>=5) then 1 else  0 end),0) as paiedorders,
isnull(sum(case when status=12 then 1 else  0 end),0) as finishOrders,
isnull(sum(case when status=12 then productprice else  0 end),0) as totalprices
from #t

--按条件查询发展的会员的订单总数
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' 1=1 '

if @endtime is not null
begin
select @endtime=dateadd(day,1,@endtime)
end

if @begintime is not null and @endtime is not null
select @where =@where +' and ordertime >='''+cast(@begintime as varchar(30)) +''' and ordertime< '''+cast(@endtime as varchar(30))+''''
else if  @begintime is not null
select @where=@where+' and ordertime>= '''+cast(@begintime as varchar(30))+''''
else if  @endtime is not null
select @where=@where+' and ordertime< '''+cast(@endtime as varchar(30))+''''

if isnull(@membername,'')<>''
select @where=@where +' and membername= '''+@membername+''''

select @sqlstr='select *from(
select *,Row_number() over(order by orderid desc) as rowno 
from #t where ' + @where + ') as ma where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

Execute(@sqlstr)

--获取总记录数和总页数
declare @totalcount int 
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by orderid desc) as rowno from #t where ' + @where + ') as p)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch 
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AppForm_Add]    脚本日期: 04/09/2012 18:26:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-09-06>
-- Description:	<客户申请退款或 申请退款，退换货，返修时向这个表插入数据>
-- Debug:
/*
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AppForm_Add]
	@ano varchar(20) = NULL,
	@orderid int = NULL,
	@orderno varchar(50) = NULL,
	@memberid int = NULL,
	@applicant varchar(50) = NULL,
	@mobile varchar(20) = NULL,
	@refundtype tinyint = NULL,
	@type int = NULL,--1退货，2换货，3返修，4退款
	@reason varchar(200) = NULL,
	@DeductMoney decimal(18, 2) = NULL,
	@refundmoney decimal(18, 2) = NULL,
	@BankName varchar(50) = NULL,
	@BankAccount varchar(50) = NULL,
	@AccountName varchar(50) = NULL,
	@ReceiverName varchar(50) = NULL,
	@receiverphone varchar(50) = NULL,
	@receiverpostalcode varchar(20) = NULL,
	@receiveraddress varchar(255) = NULL,
	@isconfirm int = 0,
	@confirmtime datetime = NULL,
	@isreturn bit = 0,
	@returnconfirm bit = 0,
	@issend bit = 0,
	@sendconfirm bit = 0,
	@canrefund bit = 0,
	@isrefunded bit = 0,
	@refundtime datetime = NULL,
	@iscompleted int = 0,
	@adduser int = NULL,
	@addusername varchar(50) = NULL,
	@addtime datetime = NULL,
	--退换货返修时要提供以下数据
	@gids varchar(1000)=null,--包含多个goodsid,格式如 123,124,125
	@pids varchar(1000)=null,--包含多个productid
	@pnos varchar(8000)=null,--包含多个productno
	@pnames varchar(8000)=null,--包含多个商品名称
	@pnums varchar(1000)=null,--包含多个商品的退货数量
	@errorflag int output,
	@errorMsg varchar(200) output
AS
if @type<4 --前台客户申请退换货返修,根据商品数量跟价格算出价格
begin
--检测订单是否可以退换货返修，在XpProc_OrderProduct_Get中判断

--生成具有货品ID跟货品数量的表
select * into #t1 from SplitToTable_Func(@gids,',')
select * into #t2 from SplitToTable_Func(@pnums,',')
select #t1.value as gid ,#t2.value as quantity  into #t3 from #t1,#t2 where #t1.id=#t2.id
--检查要退换货返修的货品ID，退换货数量
declare @gidcount1 int --退换的货品的总数
declare @gidcount2 int --符合退换的货品数
select @gidcount1=count(value)from #t1
select @gidcount2=count(goodsid),@orderid=max(orderid) from orderproduct op,#t3 
where #t3.gid= op.goodsid and op.quantity>=#t3.quantity and orderno=@orderno and memberid=@memberid
if(@gidcount1<>@gidcount2)
begin
select @errorflag=1
select @errorMsg='货品或数量有误'
return 
end
--连接OrderProuduct表，查找到一个货品对应的商品名称，编号等，并计算出相应的金额
select productno,productid,productname,goodsid,unitprice*#t3.quantity as subprice,#t3.quantity,cast(lessmoney/op.quantity as decimal(18,2))*#t3.quantity as lessmoney into #t4
from orderproduct op,#t3 where #t3.gid=op.goodsid and orderid=@orderid
--退货原始金额
select @refundmoney=sum(subprice)from #t4
end
else    --前台客户要求退款，只有已付款且没有发货的商品，且servicestatus=0 才可以退款
begin
select * into #t5 from orders where orderno=@orderno and memberid=@memberid --测试订单所在的状态，不满足则退出且给出提示信息
if not exists( select orderid from #t5)
begin
select @errorflag=1
select @errorMsg='订单不存在，不可提交退款!'
return
end
if exists (select orderid from #t5 where status<2)
begin
select @errorflag=1
select @errorMsg='订单还未付款，不可提交退款！'
return
end
if exists (select orderid from #t5 where status=6)
begin
select @errorflag=1
select @errorMsg='您好，货物已经出库，请您联系客服协助退款，谢谢！'
return
end
if exists (select orderid from #t5 where paytype>=5)
begin
select @errorflag=1
select @errorMsg='该订单为先货后款订单，不允许退款！'
return
end
if exists (select orderid from #t5 where status not between 2 and 5)
begin
select @errorflag=1
select @errorMsg='您好，此订单已取消或已完成，不可退款申请！'
return
end
if exists (select orderid from #t5 where servicestatus in(14,15))
begin
select @errorflag=1
select @errorMsg='您好，此订单正在申请退款或退款中，不可再提交退款申请!'
return
end
if exists (select orderid from #t5 where servicestatus=16)
begin
select @errorflag=1
select @errorMsg='您好，此订单已完成退款，不可再提交退款申请!'
return
end
if exists (select orderid from #t5 where servicestatus=17)
begin
select @errorflag=1
select @errorMsg='您好，此订单退款申请已关闭，不可再提交退款申请!'
return
end
select *from #t5 where orderno=@orderno and memberid=@memberid and status between 2  and 5 and paytype<=4
select @refundmoney=totalprice,@orderid=orderid from #t5
end

--生成ano编号
declare @appcount int
Select @appcount=count(aid)+1 from appform Where DateDiff(dd,addtime,GetDate())=0 
select @ano=CONVERT(varchar(8), getdate(), 112 )
select @ano=@ano + right('00'+ cast(@appcount as nvarchar(10)),3)


begin try
begin tran
INSERT appform(ano, orderid, orderno, memberid, applicant, mobile, refundtype, type, reason, DeductMoney, refundmoney, BankName, BankAccount, AccountName, ReceiverName, receiverphone, receiverpostalcode, receiveraddress, isconfirm, confirmtime, isreturn, returnconfirm, issend, sendconfirm, canrefund, isrefunded, refundtime, iscompleted, adduser, addusername, addtime)
VALUES (@ano, @orderid, @orderno, @memberid, @applicant, @mobile, @refundtype, @type, @reason,@DeductMoney, @refundmoney, @BankName, @BankAccount, @AccountName, @ReceiverName, @receiverphone, @receiverpostalcode, @receiveraddress, @isconfirm, @confirmtime, @isreturn, @returnconfirm, @issend, @sendconfirm, @canrefund, @isrefunded, @refundtime, @iscompleted, @adduser, @addusername, getDate())
declare @aid int 
select @aid=@@identity

if @type<4
insert apppdt(aid,ano,productid,productno,productname,Goodsid,Goodsname,quantity,Price,pmtinfo,giftinfo)
select @aid,@ano,productID,productno,productname,goodsid,'',quantity,subprice,'','' from #t4

declare @oprule varchar(20),@opdesc varchar(20)
select @oprule='顾客'
select @opdesc = case @type
when '1' then ' 顾客有退货申请。'
when '2' then '顾客有换货申请。'
when '3' then '顾客有返修申请。'
when '4' then '顾客有退款申请。'
end
--orders表中的servicestatus的状态
--1	客户申请退货
--2	退货中
--3	退款中
--4退款成功
--5	申请关闭(退货)				
--6客户申请换货
--7换货中	
--8换货完成
--9申请关闭(换货)
--10客户申请返修
--11返修中
--12返修成功
--13申请关闭(返修)
--14 客户申请退款
--15 退款中
--16退款完成
--17申请关闭(直接退款)	
if(@type=1)
update orders set servicestatus=1 where orderid=@orderid
else if(@type=2)
update orders set servicestatus=6 where orderid=@orderid
else if(@type=3)
update orders set servicestatus=10 where orderid=@orderid
else if(@type=4)
update orders set servicestatus=14 where orderid=@orderid
--插入记录日志
exec XpProc_AppOpLog_Add @aid,@ano,@memberid,@applicant,@oprule,@opdesc,'',0
select @errorflag=0
select @errorMsg='提交成功'
commit tran
end try

begin catch
rollback tran
select @errorflag=1
--select @errorMsg='操作失败'
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
end catch

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AppForm_Get]    脚本日期: 04/09/2012 18:26:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-09-06>
-- Description:	<管理后台列出申请表>
-- Debug:
/*
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AppForm_Get]
	@pagesize int=10,--每页显示商品数
	@pageno int=1,--页码
	@isconfirm varchar(2)=null,
    @keytype varchar(2)=null,
	@keyword varchar(20)=null,
	@iscompleted varchar(2)=null,
	@type varchar(2)=null,
    @isReturn varchar(2)=null,
    @returnConfirm varchar(2)=null,
    @isSend varchar(2)=null,
    @sendConfirm varchar(2)=null,
    @canRefund varchar(2)=null,
    @isRefunded varchar(2)=null,
    @starttime varchar(20)=null,
    @endtime varchar(20)=null,
	@totalpage int =null output,--总页数
	@totalcount int output,--总记录数
	@errorflag int output,
	@errormsg varchar(200) output
AS
begin
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = '1=1'

if isnull(@isconfirm,-1)<>-1
select @where=@where+' and isconfirm= '+ @isconfirm

--构造查询条件
declare @temp varchar(1000)
select @temp=''
if isnull(@keyword,'')<>''
begin
	if isnull(@keytype,-1)<>-1
	select @temp=case @keytype when '0' then ' and applicant like ''%' when '1' then ' and addusername like ''%' when '2' then ' and orderno like ''%' end
	select @where=@where+@temp+ @keyword+'%'''
end

if isnull(@iscompleted,-1)<>-1
begin
select @where=@where+' and iscompleted= '+ @iscompleted
end

if isnull(@type,-1)<>-1
begin
--select @temp=case @type when '0' then ' and type=1' when '1' then '  and type=2' when '2' then ' and type=3' end
select @temp=' and type='+@type
select @where=@where+@temp
end

if isnull(@isReturn,-1)<>-1
select @where=@where+' and isReturn= '+ @isReturn

if isnull(@returnConfirm,-1)<>-1
select @where=@where+' and returnConfirm= '+ @returnConfirm

if isnull(@isSend,-1)<>-1
select @where=@where+' and isSend= '+ @isSend

if isnull(@sendConfirm,-1)<>-1
select @where=@where+' and sendConfirm= '+ @sendConfirm

if isnull(@canRefund,-1)<>-1
select @where=@where+' and canRefund= '+ @canRefund

if isnull(@isRefunded,-1)<>-1
select @where=@where+' and isRefunded= '+ @isRefunded

if isnull(@starttime,'')<>''
select @where=@where+' and addtime >='''+@starttime+''''

if isnull(@endtime,'')<>''
select @where=@where+' and addtime <='''+@endtime+''''

select @sqlstr='select * from(
select ANo,OrderNo,Applicant,Mobile,Type,IsConfirm,IsReturn,ReturnConfirm,CheckConfirm,IsSend,SendConfirm,CanRefund,IsRefunded,IsCompleted,Row_number() over(order by aid desc) as rowno 
from Appform where '+ @where + ') as p where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

--print @sqlstr
--insert into log(content) values(@sqlstr)
--select *from log order by addtime desc 
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by aid desc) as rowno from appform where ' + @where + ') as p)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)
--select @totalcount,@totalpage
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END










GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AppForm_Update]    脚本日期: 04/09/2012 18:26:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[XpProc_AppForm_Update]
--	@orderid int =null,--订单ID，更改状态时要同步更改Orders表中的ServiceStatus
	@aid int=null,
	@ano varchar(20) = NULL,
	@memberid int = NULL,
	@applicant varchar(50) = NULL,
	@operation varchar(20),--操作，不同的操作要更改不同的状态
	@status int=null,--更改后的状态
	@type int,--1退货，2换货  3返修
	@remark varchar(200)=null,--日志备注
	@errorflag int output,
	@errormsg varchar(200) output
AS
begin
set nocount on
Begin try
--写日志用到的一些变量
declare @oprule varchar(20)--操作角色
declare @logstatus int --appoplog的状态
select @oprule='管理员'
declare @opdesc varchar(500)--操作描述
--orders表中的servicestatus的状态
--1	客户申请退货
--2	退货中
--3	退款中
--4退款成功
--5	申请关闭(退货)				
--6客户申请换货
--7换货中	
--8换货完成
--9申请关闭(换货)
--10客户申请返修
--11返修中
--12返修成功
--13申请关闭(返修)
--14 客户申请退款
--15 退款中
--16退款完成
--17申请关闭(直接退款)

--appoplog日志的status状态
--0 未审核
--1 审核已过
--2 审核未过
--3 客户寄回要处理的商品
--4 不同意退换返修
--5 同意换货返修
--6 同意退货
--7 商家寄回未处理的商品
--8 客户签收未处理的商品
--9 商家寄回收处理后的商品
--10 客户签收处理后的商品
--11 退款中
--12 已退款
if @operation='isconfirm' --审核申请 1审核已过 2审核未过，要更改orders表中的servicestatus状态
begin
	if(@status=1)
	begin
		if(@type=1)
		begin
			update AppForm set confirmtime=getdate(),isconfirm=1 where aid=@aid
--			update orders set servicestatus=2 where orderid=@orderid
			update orders set servicestatus=2 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
			select @opdesc ='顾客退货申请，审核通过'
			select @logstatus=1
		end
		else if(@type=2)
		begin
			update AppForm set confirmtime=getdate(),isconfirm=1 where aid=@aid
			update orders set servicestatus=7 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
			select @opdesc ='顾客换货申请，审核通过'
			select @logstatus=1
		end
		else if(@type=3)
		begin
			update AppForm set confirmtime=getdate(),isconfirm=1 where aid=@aid
			update orders set servicestatus=11 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
			select @opdesc ='顾客返修申请，审核通过'
			select @logstatus=1
		end
		else if(@type=4)
		begin
			update AppForm set confirmtime=getdate(),isconfirm=1,checkconfirm=1,checktime=getDate(),canrefund=0 where aid=@aid
			update orders set servicestatus=15 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
			select @opdesc ='顾客退款申请，审核通过'
			select @logstatus=1
		end	end
	else if @status=2 --不同意退换货返修等，把交易置为关闭
	begin
		if(@type=1)
		begin
			update AppForm set confirmtime=getdate(),isconfirm=2,iscompleted=1 where aid=@aid
			update orders set servicestatus=5 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
			select @opdesc ='顾客退货申请，审核不通过'
			select @logstatus=2
		end
		else if(@type=2)
		begin
			update AppForm set confirmtime=getdate(),isconfirm=2,iscompleted=1 where aid=@aid
			update orders set servicestatus=9 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
			select @opdesc ='顾客换货申请，审核不通过'
			select @logstatus=2
		end
		else if(@type=3)
		begin
			update AppForm set confirmtime=getdate(),isconfirm=2,iscompleted=1 where aid=@aid
			update orders set servicestatus=13 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
			select @opdesc ='顾客返修申请，审核不通过'
			select @logstatus=2
		end
		else if(@type=4)
		begin
			update AppForm set confirmtime=getdate(),isconfirm=2,iscompleted=1 where aid=@aid
			update orders set servicestatus=17 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
			select @opdesc ='顾客退款申请，审核不通过'
			select @logstatus=2
		end	end
end
else if @operation='checkconfirm'--检查寄回的商品是否符合退换修条件
begin
	if(@status=1)--符合条件
	begin
		if(@type=1)--同意退货
		begin
		update appform set returnconfirm=1,checkconfirm=1,checktime=getDate() where aid=@aid
		select @opdesc ='商家收到寄回的商品，同意退货'
		select @logstatus=6
		end
		else if(@type=2)--同意换货
		begin
		update appform set returnconfirm=1,checkconfirm=1,checktime=getDate() where aid=@aid
		select @opdesc ='商家收到寄回的商品，同意换货'
		select @logstatus=5
		end
		else if(@type=3)--同意返修
		begin
		update appform set returnconfirm=1,checkconfirm=1,checktime=getDate() where aid=@aid
		select @opdesc ='商家收到寄回的商品，同意维修'
		select @logstatus=5
		end
	end
	else --不符合条件
	begin
		if(@type=1)--不同意退货
		begin
		select @opdesc ='商家收到寄回的商品，不同意退货'
		select @logstatus=4
		end
		else if(@type=2)--换货
		begin
		select @opdesc ='商家收到寄回的商品，不同意换货'
		select @logstatus=4
		end
		else if(@type=3)--返修
		begin
		select @opdesc ='商家收到寄回的商品，不同意维修'
		select @logstatus=4
		end
		update appform set returnconfirm=1,checkconfirm=2,checktime=getDate() where aid=@aid
	end
end
else if @operation='isreturn'--客户寄回商品
begin
	select @oprule='客户'
	if(@type=1)--退货
	begin
	select @opdesc ='客户寄回要退货的商品'
	select @logstatus=3
	end
	else if(@type=2)--换货
	begin
	select @opdesc ='客户寄回要换货的商品'
	select @logstatus=3
	end
	else if(@type=3)--返修
	begin
	select @opdesc ='客户寄回要返修的商品'
	select @logstatus=3
	end
	update appform set isreturn=1,returntime=getDate()where aid=@aid
end
else 
if @operation='isSend'--商家寄回商品,1商家直接退回的商品 2维修后或换货后的商品
begin
	declare @checkconfirm int
	select @checkconfirm=checkconfirm from appform(nolock) where aid=@aid
	if(@checkconfirm=2)--商家直接退回的不符合退换修的商品
	begin
		if(@type=1)--退货
		begin
		select @opdesc ='商家直接寄回收到的商品'
		select @logstatus=7
		end
		else if(@type=2)--换货
		begin
		select @opdesc ='商家直接寄回收到的商品'
		select @logstatus=7
		end
		else if(@type=3)--返修
		begin
		select @opdesc ='商家直接寄回收到的商品'
		select @logstatus=7
		end
	end
	else if(@checkconfirm=1)
	begin
		if(@type=2)--换货
		begin
		select @opdesc ='商家寄回换货后的商品'
		select @logstatus=9
		end
		else if(@type=3)--返修
		begin
		select @opdesc ='商家寄回维修后的商品'
		select @logstatus=9
		end
	end
	update appform set issend=1,sendtime=getDate()where aid=@aid
end
else if @operation='sendconfirm'--客户签收商品有三种情况，1商家直接退回的商品 2维修后的商品 3换货的商品 客户签收后要更新Orders 中的ServiceStatus的状态
begin
	select @oprule='客户'
	select @checkconfirm=checkconfirm from appform where aid=@aid
	if(@checkconfirm=2)--商家直接退回的不符合退换修的商品,签收后售后状态置为关闭
	begin
		if(@type=1)--退货
		begin
		select @opdesc ='客户签收直接退回的商品'
		select @logstatus=8
		update orders set servicestatus=5 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
		end
		else if(@type=2)--换货
		begin
		select @opdesc ='客户签收直接退回的商品'
		select @logstatus=8
		update orders set servicestatus=9 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
		end
		else if(@type=3)--返修
		begin
		select @opdesc ='客户签收直接退回的商品'
		select @logstatus=8
		update orders set servicestatus=13 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
		end
		update appform set sendconfirm=1 ,confirmtime=getDate(),iscompleted=1 where aid=@aid
		end
	else
	begin if(@checkconfirm=1)
		if(@type=2)--换货
		begin
		select @opdesc ='客户签收换货后的商品'
		select @logstatus=10
		update orders set servicestatus=8 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
		end
		else if(@type=3)--返修
		begin
		select @opdesc ='客户签收维修后的商品'
		select @logstatus=10
		update orders set servicestatus=12 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
		end
		update appform set sendconfirm=1 ,confirmtime=getDate(),iscompleted=2 where aid=@aid
	end
end
else if @operation='refund'--写入退款
begin
  	select @opdesc ='增加退款记录,等待退款'
	select @logstatus=11
	update orders set servicestatus=3 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
	update appform set canrefund=1 where aid=@aid
end
else if @operation='isRefund'--退款
begin
  	select @opdesc ='商家已退款'
	select @logstatus=12
	update orders set servicestatus=4 from orders,appform where appform.orderid=orders.orderid and appform.aid=@aid 
	update appform set isrefunded=1,refundtime=getDate()where aid=@aid
end

--写日志
exec XpProc_AppOpLog_Add @aid,@ano,@memberid,@applicant,@oprule,@opdesc,@remark,@logstatus
select @errorFlag=0
select @errorMsg='操作成功'
End Try

Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AppFormRelateInfo_Get]    脚本日期: 04/09/2012 18:26:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-09-13>
-- Description:	<管理后台列出相关表的信息>
-- Debug:
/*
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AppFormRelateInfo_Get]
	@aid int=null,
	@ano varchar(20) = NULL,
	@errorflag int output,
	@errormsg varchar(200) output
AS
begin
set nocount on
Begin try
select aid,ano,orderid,orderno,memberid,applicant,mobile,refundtype,type,reason,deductmoney,refundmoney,bankname,bankaccount,
accountname,receivername,receiverphone,receiverpostalcode,receiveraddress,isconfirm,confirmtime,isreturn,returnconfirm,returntime,
checkconfirm,checktime,issend,sendtime,sendconfirm,canrefund,isrefunded,refundtime,iscompleted,adduser,addusername,addtime 
from appform(nolock) where ano=@ano
select *from apppdt where ano=@ano
select oprule,opdesc+' ' +remark as opdesc,optime from appoplog where ano=@ano order by optime asc
select *from appshipping(nolock) where ano=@ano
select *from apprefund(nolock) where ano=@ano
select @errorflag=0
select @errormsg = ''
End Try
Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END











GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AppOpLog_Add]    脚本日期: 04/09/2012 18:26:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2010-09-13>
-- Description:	<记录对售后服务的操作>
-- =============================================
CREATE PROC [dbo].[XpProc_AppOpLog_Add]
@aid int=null,--申请表ID
@ano varchar(20)=null,--申请表编号
@operator int=Null,--操作员的会员ID
@operatorname varchar(50)=null, --操作员
@OPRule varchar(20) = NULL,--操作角色 顾客，系统，商家,管理员
@OPDesc varchar(500) = NULL,--操作描述
@Remark varchar(200) =NULL,--操作备注
@Status int--状态
AS
begin
insert appoplog(aid,ano,operator,operatorname,oprule,opdesc,optime,Remark,status)values
(@aid,@ano,@operator,@operatorname,@OPRule,@OPDesc,getDate(),@Remark,@Status)
end









GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AppRefund_Add]    脚本日期: 04/09/2012 18:26:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-09-15>
-- Description:	<用于收到顾客发回退货商品，插入退款记录>
-- Debug:
/*
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AppRefund_Add]
@adminID int,--操作员ID
@applicant varchar(50),--操作员姓名
@deductMoney decimal(18,2),--退款要扣减的金额
@remark varchar(200),--操作备注
@aid int=null,
@ano varchar(20) = NULL,
@errorflag int output,
@errorMsg varchar(200) output
AS
begin
begin try
begin tran
select *from appform
--插入退款信息
--INSERT apprefund(aid,ano,orderid,orderno,RefundType,money,bankname,bankaccount,accountname,memberid,realname,mobile,isconfirm,
--confirmtime,isrefunded,refundtime,addTime)
--VALUES (@aid,@ano,@orderid,@orderno,@refundtype,@money,@bankname,@bankaccount,@accountname,@memberid2,@realname,@mobile,1,getDate(),0,null,getDate())

INSERT apprefund(aid,ano,orderid,orderno,RefundType,money,bankname,bankaccount,accountname,memberid,realname,mobile,isconfirm,
confirmtime,isrefunded,refundtime,addTime)
select aid,ano,orderid,orderno,refundtype,refundmoney-@deductMoney,bankname,bankaccount,accountname,memberid,applicant,mobile,1,getDate(),0,null,getDate()
from appform(nolock) where aid=@aid

----更新AppForm表中的deductMoney,canrefund
update appform set deductMoney=@deductMoney,canrefund=1 where aid=@aid

exec XpProc_AppForm_Update @aid,@ano,@adminID,@applicant,'refund',null,1,@remark,@errorflag output,@errormsg output

select @errorflag=0
select @errorMsg='操作成功'
commit tran
end try
begin catch
rollback tran
select @errorflag=1
--select @errorMsg='操作失败'
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
end catch
end

--set ANSI_NULLS ON
--set QUOTED_IDENTIFIER ON
--GO
---- =============================================
---- Author:		<liwenhai>
---- Create date: <2011-09-15>
---- Description:	<用于收到顾客发回退货商品，插入退款记录>
---- Debug:
--/*
--*/
---- =============================================
--ALTER PROCEDURE [dbo].[XpProc_AppRefund_Add]
--@memberid int,
--@applicant varchar(50),
--@deductMoney decimal(18,2),--退款扣减金额
--@remark varchar(200),--操作备注
--@aid int=null,
--@ano varchar(20) = NULL,
--@orderid int =null,
--@orderNo varchar(50)=null,
--@refundtype int =null,
--@money decimal(18,2)=null,
--@bankname varchar(50)=null,
--@bankaccount varchar(50)=null,
--@accountname varchar(50)=null,
--@memberid2 int, --退款的会员ID
--@realname varchar(50)=null,
--@mobile	varchar(50)=null,
--@errorflag int output,
--@errorMsg varchar(200) output
--AS
--begin
--begin try
--begin tran
--select *from appform
----插入退款信息
----INSERT apprefund(aid,ano,orderid,orderno,RefundType,money,bankname,bankaccount,accountname,memberid,realname,mobile,isconfirm,
----confirmtime,isrefunded,refundtime,addTime)
----VALUES (@aid,@ano,@orderid,@orderno,@refundtype,@money,@bankname,@bankaccount,@accountname,@memberid2,@realname,@mobile,1,getDate(),0,null,getDate())
--
--INSERT apprefund(aid,ano,orderid,orderno,RefundType,money,bankname,bankaccount,accountname,memberid,realname,mobile,isconfirm,
--confirmtime,isrefunded,refundtime,addTime)
--select aid,ano,orderid,orderno,refundtype,@money,bankname,bankaccount,accountname,@memberid2,applicant,mobile,1,getDate(),0,null,getDate()from appform
--
------更新AppForm表中的deductMoney,canrefund
--update appform set deductMoney=@deductMoney,canrefund=1 where aid=@aid
--
--exec XpProc_AppForm_Update @aid,@ano,@memberid,@applicant,'refund',null,1,@remark,@errorflag output,@errormsg output
--
--select @errorflag=0
--select @errorMsg='操作成功'
--commit tran
--end try
--begin catch
--rollback tran
--select @errorflag=1
----select @errorMsg='操作失败'
--select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
--end catch
--end
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AppRefund_Get]    脚本日期: 04/09/2012 18:26:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-09-22>
-- Description:	<管理后台列出退款表>
-- Debug:
/*
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AppRefund_Get]
	@pagesize int=10,--每页显示退款数
	@pageno int=1,--页码
    @keytype varchar(2)=null,
	@keyword varchar(20)=null,
	@isconfirm varchar(2)=null,
    @isRefunded varchar(2)=null,
	@refundtype varchar(2)=null,
    @starttime varchar(20)=null,
    @endtime varchar(20)=null,
	@totalpage int =null output,--总页数
	@totalcount int output,--总记录数
	@errorflag int output,
	@errormsg varchar(200) output
AS
begin
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = '1=1'

--构造查询条件
declare @temp varchar(1000)
select @temp=''
if isnull(@keyword,'')<>''
begin
	if isnull(@keytype,-1)<>-1
	select @temp=case @keytype when '0' then ' and realname like ''%' when '1' then ' and orderno like ''%' when '2' then ' and orderno like ''%' end
	select @where=@where+@temp+ @keyword+'%'''
end

if isnull(@isconfirm,-1)<>-1
select @where=@where+' and isconfirm= '+ @isconfirm

if isnull(@refundtype,-1)<>-1
select @where=@where+' and refundtype= '+ @refundtype

if isnull(@isRefunded,-1)<>-1
select @where=@where+' and isRefunded= '+ @isRefunded

if isnull(@starttime,'')<>''
select @where=@where+' and addtime >='''+@starttime+''''

if isnull(@endtime,'')<>''
select @where=@where+' and addtime <='''+@endtime+''''

select @sqlstr='select * from(select RID,AID,ANo,OrderID,OrderNo,Money,BankName,BankAccount,AccountName,MemberID,RealName,Mobile,IsConfirm,ConfirmTime,
RefundType,IsRefunded,RefundTime,Row_number() over(order by RID desc) as rowno 
from AppRefund where '+ @where + ') as p where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
--insert log(content)values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by rid desc) as rowno from apprefund where ' + @where + ') as p)'
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch 
END

--select * ,
--case isrefunded when 1  then '已退款'  
--else  case isconfirm when 1 then '已确认' else '未确认' end  end as status from apprefund



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AppRefund_Update]    脚本日期: 04/09/2012 18:26:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-09-22>
-- Description:	<后台审核退款申请或提交退款，都要调用此存储过程更新退款表的状态>
-- Debug:
/*
	被XpProc_ReceivePay_Add存储过程调用
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AppRefund_Update]
	@aid int=null,
	@ano varchar(20) = NULL,
	@memberid int = NULL,
	@applicant varchar(50) = NULL,
	@operation varchar(20),--操作，不同的操作要更改不同的状态
	@status int=null,--更改后的状态
	@remark varchar(200)=null,--日志备注
	@errorflag int=null output,
	@errormsg varchar(200)=null output
AS
begin
set nocount on
Begin try
--写日志用到的一些变量
declare @oprule varchar(20)--操作角色
declare @logstatus int --appoplog的状态
select @oprule='管理员'
declare @opdesc varchar(500)--操作描述
if @operation='isconfirm' --审核申请 1审核已过 2审核未过
begin
	if(@status=1)
	begin
		update AppRefund set confirmtime=getdate(),isconfirm=1 where aid=@aid
		select @opdesc ='顾客退款申请，审核通过'
		select @logstatus=1
	end
	else if @status=2
	begin
		update AppRefund set confirmtime=getdate(),isconfirm=2 where aid=@aid
		update AppForm set iscompleted=1 where aid=@aid
		select @opdesc ='顾客退款申请，审核不通过'
		select @logstatus=1
	end
end
else if @operation='isrefund'--退款操作
begin
	declare @orderid int,@type int,@refundtype int,@bankaccount varchar(50),@accountname varchar(50)
	select @orderid=orderid,@type=type,@refundtype=refundtype,@bankaccount=bankaccount,@accountname=accountname from appform(nolock) where aid=@aid
	if(@refundtype=1)--退款到账户
  	select @opdesc ='已退款,到会员账户余额。'
	else--退款到银行卡中
  	select @opdesc ='已退款,到会员的银行卡。'+'银行卡账号：'+@bankaccount
	select @logstatus=12
	--退货或退款后，要更改订单的状态
	if @type=1 --退货
	update orders set servicestatus=4 where orderid=@orderid
	else if @type=4 --直接退款
	update orders set servicestatus=16 where orderid=@orderid

	update apprefund set isrefunded=1,refundtime=getDate() where aid=@aid
	update appform set isrefunded=1,refundtime=getDate(),iscompleted=2 where aid=@aid
end

--写日志
exec XpProc_AppOpLog_Add @aid,@ano,@memberid,@applicant,@oprule,@opdesc,@remark,@logstatus
select @errorFlag=0
select @errorMsg='操作成功'
End Try

Begin Catch
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
declare @err varchar(1000),@severity int 
set @err=ERROR_MESSAGE();
set @severity=ERROR_SEVERITY();
RAISERROR(@err,@severity,1);
End Catch
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AppShipping_Add]    脚本日期: 04/09/2012 18:26:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-09-15>
-- Description:	<写入物流信息的3种情形：1.用于前台顾客退回商品时调用。2.后台商家收到顾客退回的商品，
--当不满足退换返条件时发回给顾客。3.后台商家发回返修后的商品时调用>
-- Debug:
/*
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AppShipping_Add]
@remark varchar(200),--操作备注
@memberid int,
@applicant varchar(50),
@aid int=null,
@ano varchar(20) = NULL,
@shippname varchar(50)=null,
@shippno varchar(50)=null,
@shipptime datetime=null,
@shiptype varchar(50)=null,
@shippprice	decimal(18,2)=null,
@sendername	varchar(50)=null,
@senderphone varchar(50)=null,
@SenderPostalcode varchar(20)=null,
@senderaddress varchar(255)=null,
@receivername varchar(50)=null,
@receiverphone	varchar(50)=null,
@receiverpostalcode	varchar(20)=null,
@receiveraddress varchar(255)=null,
@isCustomer bit=null,--用于标识是前台顾客的操作，还是后台商家的操作
--@isCheck bit=null,--用于标识商家是否接受顾客发回的要求退换返的商品
@type int =null,--1是退货，2是换货，3是返修
@errorflag int output,
@errorMsg varchar(200) output
AS

begin try
begin tran
--插入发货信息
INSERT appshipping( aid,ano,shippname,shippno,shipptime,shiptype,shippprice,sendername,senderphone,SenderPostalcode,senderaddress,
receivername,receiverphone,receiverpostalcode,receiveraddress,addTime)
VALUES (@aid,@ano,@shippname,@shippno,isnull(@shipptime,getDate()),@shiptype,@shippprice,@sendername,@senderphone,@SenderPostalcode,@senderaddress,
@receivername,@receiverphone,@receiverpostalcode,@receiveraddress,getDate())

if @iscustomer=1 --前台顾客发回商品
begin
--更改AppForm表的相关状态
exec XpProc_AppForm_Update @aid,@ano,@memberid,@applicant,'isreturn',null,@type,@remark,@errorflag output,@errormsg output
end
--else if @ischeck=1 --后台商家发回返修或换货的商品
--begin
--exec XpProc_AppForm_Update @aid,@ano,@memberid,@applicant,'issend',null,@type,@remark,@errorflag output,@errormsg output
--end
--else if @ischeck=0 --直接退回不符合退换返条件的商品,先签收商品再退回去
else
begin
exec XpProc_AppForm_Update @aid,@ano,@memberid,@applicant,'issend',null,@type,@remark,@errorflag output,@errormsg output
end
select @errorflag=0
select @errorMsg='操作成功'
commit tran

end try
begin catch
rollback tran
select @errorflag=1
--select @errorMsg='操作失败'
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
end catch










GO
/****** 对象:  StoredProcedure [dbo].[XpProc_AreaShipping_Get]    脚本日期: 04/09/2012 18:26:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<hakkas>
-- Create date: <2011-03-12>
-- Description:	<获取地区配送方式及运费>
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110827                             
content:                                
1.添加参数@shiptype,用于获取支持货到付款的配送方式                                
*/
/*
引用该存储过程的存储过程：
1、XpProc_Checkout_Init
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_AreaShipping_Get]
@areaid int=-1, --地区ID
@areaidforprice int=-1,--根据这个地区ID查找配送价格
@pdtPrice money,--商品总价
@weight decimal(18,2),--商品重量
@shiptype int=0,--配送类型0:所有配送方式；1:支付货到付款
@sid int --商家ID
AS
BEGIN
--exec XpProc_AreaShipping_Get 237,100,2,0
--declare @areaid int,@sid int,@weight decimal
--select @areaid=237,@sid=0,@weight=2

select @pdtPrice=isnull(@pdtPrice,0),@weight=isnull(@weight,0)

select top 0 convert(int,shippingid) as shippingid,name,description,remark=convert(varchar(100),''),price as expression,price=convert(decimal(18,2),0)
into #t
from shipping(nolock)

if @areaid>0
begin
	--根据地区查找配送方式
	if @shiptype=0
	begin
	declare @shipps varchar(50)
	select @shipps=Shipps from ShippingArea(nolock) where ShippingAreaID=@areaid  
	--insert into log(content) values(convert(varchar(10),@areaid)+'|'+convert(varchar(10),@weight)+'|'+convert(varchar(10),@sid)+'|'+convert(varchar(10),@pdtPrice)+'|'+@shipps)
	insert into #t
	select s.shippingid,s.name,s.description,remark=convert(varchar(100),''),
	replace(replace(isnull(sp.ShippingExpression,s.price),'c','ceiling'),'w',cast(@weight as nvarchar(20))) as expression,
	price=convert(decimal(18,2),0)
	from Shipping s(nolock)
	left join ShippingPrice sp(nolock)
	on s.shippingid=sp.shippingid and sp.supplierid=@sid and sp.shippingareaid=@areaid
	where s.ShippingID in (select value from SplitToTable_Func(@shipps,','))
	end
	else  --货到付款的配送方式
	begin
	insert into #t
	select s.shippingid,s.name,s.description,remark=convert(varchar(100),''),
	replace(replace(isnull(sp.ShippingExpression,s.price),'c','ceiling'),'w',cast(@weight as nvarchar(20))) as expression,
	price=convert(decimal(18,2),0)
	from Shipping s(nolock)
	left join ShippingPrice sp(nolock)
	on s.shippingid=sp.shippingid and sp.supplierid=@sid and sp.shippingareaid=@areaid
	where s.ShippingID in (select shippID from shipppay where shippareaid=@areaid)
	end

end
else
begin
--获取所有配送方式
insert into #t
select shippingid,name,description,remark=convert(varchar(100),''),
replace(replace(price,'c','ceiling'),'w',cast(@weight as nvarchar(20))) as expression,
price=convert(decimal(18,2),0)
from Shipping(nolock)
end


-- =============================================
--判断是否符合免运费条件开始
declare @freeType int,@leastMoney decimal(18,2)
select top 1 @freeType=FreeType,@leastMoney=LeastMoney from ShippingFree(nolock) where SupplierID=@sid
select @freeType=isnull(@freeType,0),@leastMoney=isnull(@leastMoney,99999999)
if(@freeType=0)--不免运费，要通过运费公式计算运费
begin
	print('要计算运费')
end
else if(@freeType=1)--所有地区统一最低免运费消费金额
begin
	if(@pdtPrice>@leastMoney)--商品总额大于最低消费金额
	begin
		--免运费
		update #t set remark='商品总额:'+convert(varchar(50),@pdtPrice)+'大于最低免运费金额：'+convert(varchar(50),@leastMoney)+'，免运费'
		goto result
	end
	else
	begin
		print('要计算运费')
	end
end
else--分地区设定最低免运费消费金额
begin
	select @leastMoney=Least from ShippingArea(nolock) where ShippingAreaID=@areaidforprice--获取对应地区的最低免运费消费金额
	if(@pdtPrice>=@leastMoney)--商品总额大于最低消费金额
	begin
		--免运费
		update #t set remark='商品总额:'+convert(varchar(50),@pdtPrice)+'大于最低免运费金额：'+convert(varchar(50),@leastMoney)+'，免运费'
		goto result
	end
	else
	begin
		print('要计算运费')
	end
end
--判断是否符合免运费条件结束
-- =============================================

declare @sql varchar(8000)
select @sql=''
select @sql=@sql+' when '''+expression+''' then '+expression+'' 
from #t
group by expression

--动态sql法计算运费
--select @sql
exec('update #t set price=case expression '+@sql+' end')


--返回配送方式及运费
result:
select * from #t
--drop table #t
END












GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Cart_Look]    脚本日期: 04/09/2012 18:26:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Hakkas>
-- Create date: <2010-03-12>
-- Description:	<查看购物车信息>
/*
引用该存储过程的存储过程：
1、XpProc_CartItem_Add
2、XpProc_CartPdtQty_Update
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Cart_Look] 
@cartid nvarchar(50),--购物车ID
@memberid int=-1,--会员ID
@errorflag int =0 out,--错误标志
@errormsg varchar(200)='' out--错误信息描述
AS
BEGIN
-- =============================================
declare @scorerate decimal(18,2)
select @scorerate=0.01

--获取会员对应会员组享受的折扣
declare @groupid int,--会员组ID
@groupname nvarchar(20),--会员组名称
@discount decimal(18,2)--会员组折扣
select @groupid=0
select @groupid=groupid,@groupname=mg.groupname,@discount=cast(mg.discount/100.00 as decimal(18,2)) from member m,membergroup mg where m.groupid=mg.MemberGroupID and m.memberid=@memberid
--print('获取会员对应会员组享受的折扣')
--select @groupid as '会员组ID',@discount as '会员组折扣'


--declare @cartid nvarchar(100)
--select @cartid='10a2fd6e-e9c4-4142-a9d8-41cf9c763f6c'

--0. 套餐信息
delete from suitscart where cartid=@cartid

insert into suitscart(cartid,suitid,RecordID,suitname,marketprice,memberprice,quantity,score)
select @cartid,suitid,c.RecordID,suitname,oldprice,price,c.quantity,0 score
from shoppingcart c(nolock),suit s(nolock)
where c.cartid=@cartid and c.ptype=3 and c.productid=s.suitid

--1.购物车信息
select       
p.productid,p.productno,isnull(gg.goodsname,p.productname) as productname,gg.marketprice,gg.memberprice,gg.weight,      
c.CartID,c.quantity,p.ImgFolder,p.ProductImg,
gg.weight*c.quantity subweight,      
isnull(g.pmtprice,gg.memberprice) as pmtprice,
--isnull(g.pmtprice,case when @discount<>'100' and p.IsDiscount=1 then gg.memberprice*cast(@discount/100.00 as decimal(18,2)) else null end) pmtprice,--优惠单价
isnull(g.pmtprice,gg.memberprice)*c.quantity SubMoney,--小计金额      
(gg.memberprice-isnull(g.pmtprice,gg.memberprice))*c.quantity LessMoney,--优惠金额      
 g.pmtname,g.RuleID ,g.RuleName,g.BasicType,g.SubType,      
convert(varchar(200),'') remark , 
gg.GoodsID,p.IsDiscount,1 IsDlvUnit,1 DlvUnit,MiniBuyNum,gg.Score,0 usescore,0 StowageID,1 IsOfferInvoice, 
RecordID,ProductSpecs  
,g.pmtid--活动ID
,p.supplierid   
into #cart      
from
ShoppingCart c(nolock),goods gg(nolock),product p(nolock)     
left join PmtGoodsList g      
on( p.productid=g.productid and g.BasicType='goods' and g.SubType in('discount','specialprice','limittime')--一个商品只能作一个特价或折扣
and charindex(','+convert(nvarchar(10),@groupid)+',',','+g.GroupIDs+',')>0--允许参与优惠活动的会员组才可以享受优惠
and g.balance>0
)       
where
c.productid=p.productid
and gg.goodsid=c.goodsid--增加多维规格功能  
and p.productid=gg.productid      
and c.quantity>0
and c.ptype=1--商品      
and c.cartid=@cartid

update #cart set pmtprice=memberprice*@discount,submoney=submoney*@discount,lessmoney=(memberprice-memberprice*@discount)*quantity,rulename=@groupname+':'+left(convert(varchar(10),@discount*10),3)+'折' where isnull(ruleid,0)=0 and IsDiscount=1 and @discount<>'1.00'

--2.商品购买数量控制 
select b.*      
into #MemberBookProduct      
from MemberBookPmtGoods b(nolock),#cart c(nolock)      
where 
b.RuleID=c.RuleID and c.productid=b.productid 

--2.1购买总数量限制      
select p.RuleID,p.productid,g.PmtNumber maxgoodsnumber,sum(p.quantity) goodsnumber      
into #MemberBookProduct_a--购买总数统计表      
from #MemberBookProduct p(nolock),PmtGoods g(nolock)      
where g.ruleid=p.ruleid      
and g.productid=p.productid      
and g.PmtNumber>0--限制数量
group by p.RuleID,p.productid,g.PmtNumber      
having sum(p.quantity)>=g.PmtNumber      
      
--2.2会员购买数量限制      
select p.ruleid,p.productid,memberid ,g.LimitedNumber maxmembernumber,sum(quantity) membernumber      
into #MemberBookProduct_b--个人购买统计表      
from #MemberBookProduct p(nolock) ,PmtGoods g(nolock)      
where       
g.ruleid=p.ruleid      
and g.productid=p.productid      
and g.LimitedNumber>0--限制数量      
and memberid=@memberid      
group by  p.ruleid,p.productid,memberid ,g.LimitedNumber        
having sum(p.quantity)>=g.LimitedNumber      
      
--2.3汇总      
--2.3.1      
update c set c.quantity=0,SubMoney=0,LessMoney=0,subweight=0, remark='此商品已经抢购完,谢谢您的支持，请在下次购买'                
from #cart c,#MemberBookProduct_a a(nolock)                            
where                     
c.ruleid=a.ruleid                            
and c.productid=a.productid      
      
--2.3.2      
update c set c.quantity=0,SubMoney=0,LessMoney=0,subweight=0, remark='您已超过此商品最大抢购量:'+convert(varchar(8),a.maxmembernumber)+',谢谢您的支持，请在下次购买'              
from #cart c,#MemberBookProduct_b a(nolock)                            
where                            
c.ruleid=a.ruleid                            
and c.productid=a.productid         
      
--2.3.3     
update c set c.quantity=0,SubMoney=0,LessMoney=0,subweight=0, remark='您已超过此商品最大抢购量:'+convert(varchar(8),a.LimitedNumber)+',请修改数量'              
from #cart c,PmtGoods a(nolock)                            
where                            
c.ruleid=a.ruleid                            
and c.productid=a.productid                            
and ((c.quantity> a.PmtNumber and  a.PmtNumber>0)                             
or c.quantity>a.LimitedNumber and a.LimitedNumber>0) 
    

--3.1购物车汇总，获取参与促销活动汇总信息                        
--drop table  #orderinfo                 
select l.ruleid,sum(SubMoney) totalprice,sum(quantity) totalnumber                            
into #orderinfo                            
from #cart c(nolock),PmtGoodsList l(nolock)                            
where                         
1=1                        
and                         
c.productid=l.productid        
and c.goodsid=l.goodsid                      
and l.SubType='gift'--礼品换购信息                          
group by l.ruleid    
                          
--3.2获取赠品商品信息                        
if object_id('tempdb.dbo.#gift') is not null                            
begin       
drop table #gift                            
end                                
select  floor(                        
case when isautoAdded=1 then                            
case when r.BasicType='orders' then o.totalprice                            
when r.BasicType='goods' then o.totalnumber end/minvalue  --订单满额规格可能有问题
else 1 end) giftnumber,--可获礼品数量                            
convert(varchar(200),' ') giftremark, r.BasicType,g.SubType,                       
g.ID,g.PmtName,g.RuleID,g.RuleNo,                        
g.RuleName,g.productid,g.goodsid,g.productname,p.imgfolder,p.productimg,                    
g.categoryid,g.brandid,g.brandname,g.usescore,g.score,                        
g.marketprice,g.memberprice,g.PmtPrice,g.stowageid,                        
g.PmtNumber,g.LimitedNumber,g.IsLimited,g.maxnumber,g.isselected,                        
g.gifttype,g.groupname,g.addtime,g.status,                        
--g.adduser,g.deltime,g.deluser,
g.remark,
r.PmtID,g.supplierid                     
into #gift                             
from #orderinfo o(nolock),PmtRule r(nolock),PmtGifts g(nolock),Product p(nolock)   -----------------------------这里为什么要联商品表product????????????                         
where                             
o.ruleid=r.ruleid                          
and p.productid=g.productid                          
and g.ruleid=r.ruleid                            
and r.SubType='gift'                            
and minvalue                            
<=case when r.BasicType='orders' then o.totalprice               
when r.BasicType='goods' then o.totalnumber end--起始条件                            
and (  maxvalue=0 or isautoAdded=1 or                          
convert(money,maxvalue)>case when r.BasicType='orders' then o.totalprice                            
when r.BasicType='goods' then o.totalnumber end--最大条件                            
)

--4.礼品数量限制                    
if object_id('tempdb.dbo.#MemberBookGift') is not null                            
begin                            
drop table #MemberBookGift                            
end                            
select b.*                            
into #MemberBookGift                            
from MemberBookPmtGoods b(nolock),#gift c(nolock)                            
where b.RuleID=c.RuleID                            
and c.productid=b.productid                            
                            
--4.1总数限制                           
if object_id('tempdb.dbo.#MemberBookGift_a') is not null                            
begin                            
drop table #MemberBookGift_a                            
end           
select p.RuleID,p.productid,l.PmtNumber,sum(p.quantity) SaleNumber                            
into #MemberBookGift_a                            
from #MemberBookGift p(nolock),PmtGifts l(nolock)                            
where l.RuleID=p.RuleID                            
and l.productid=p.productid                            
and l.PmtNumber>0--有限制数量                            
group by p.RuleID,p.productid,l.PmtNumber                            
having sum(p.quantity)>=l.PmtNumber                      
                            
--4.2个人数量限制                           
if object_id('tempdb.dbo.#MemberBookGift_b') is not null                            
begin                            
drop table #MemberBookGift_b                            
end                            
select p.RuleID,p.productid,memberid,l.LimitedNumber,sum(quantity) PersonalNumber                            
into #MemberBookGift_b                            
from #MemberBookGift p(nolock) ,PmtGifts l(nolock)                            
where                             
l.RuleID=p.RuleID                            
and l.productid=p.productid                            
and l.LimitedNumber>0--有限制个人购买数量                            
and memberid=@memberid                            
group by  p.RuleID,p.productid,memberid,l.LimitedNumber                              
having sum(p.quantity)>=l.LimitedNumber 
                           
--4.3 赠品信息汇总 
--4.3.1 赠品信息,此礼品已经送完完                          
update c set giftnumber=0,giftremark='此礼品已经送完'                            
from #gift c,#MemberBookGift_a a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                        
--4.3.2 赠品信息,你已超过此礼品的最大量                        
update c set giftnumber=0,giftremark='你已超过此礼品的最大量!'                            
from #gift c,#MemberBookGift_b a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                            
--4.3.3 赠品信息,最后一次仍送出                          
update c set giftnumber=a.LimitedNumber,giftremark='最后一次仍送出!'                            
from #gift c,PmtGoods a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                            
and ((c.giftnumber> a.PmtNumber and  a.PmtNumber>0)                             
or c.giftnumber>a.LimitedNumber and a.LimitedNumber>0) 

--4.4 赠品库存控制    
update c set giftnumber=0,giftremark='很抱歉，此赠品已经送完!'                            
from #gift c,goods g(nolock)                            
where            
c.goodsid=g.goodsid    
and g.Storage<=0

--5 订单总金额优惠信息                          
select top 0  TotalMoney=100, LessMoney=0,ruleid=' ' ,rulename=' ' ,moneyremark=' '                           
into #orderpromotion

--6 显示信息

--6.1 商品购物车表                            
delete from goodscart where cartid=@cartid                                                     
insert into goodscart(                     
cartid,productid,productname,productno,marketprice,memberprice,weight,                          
pmtprice,quantity,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,remark,                        
GoodsID, IsDlvUnit, DlvUnit,MiniBuyNum,Score,                        
StowageID,IsOfferInvoice,RecordID,ProductSpecs                      
,pmtid,IsDiscount,UseScore,ScoreMoney,SupplierID,RuleName,ImgFolder,ProductImg,suitid                         
)                            
select @cartid,productid,productname,productno,marketprice,memberprice,weight,                        
pmtprice,quantity,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,remark,                        
GoodsID, IsDlvUnit, DlvUnit,MiniBuyNum,Score*quantity,                        
StowageID,IsOfferInvoice,RecordID,ProductSpecs                        
,pmtid,IsDiscount,UseScore,UseScore*@scorerate,SupplierID,RuleName,ImgFolder,ProductImg,0 as suitid                           
from  #cart c(nolock)

--6.1.1添加套装商品
insert into goodscart(                     
cartid,productid,productname,productno,marketprice,memberprice,weight,                          
pmtprice,quantity,subweight,submoney,lessmoney,                            
--pmtname,ruleid,basictype,subtype,
remark,GoodsID,IsDlvUnit, DlvUnit,MiniBuyNum,Score,                        
StowageID,IsOfferInvoice,
--RecordID,ProductSpecs,pmtid,
IsDiscount,UseScore,ScoreMoney,SupplierID,ImgFolder,ProductImg,suitid,sort                        
)                            
select @cartid,p.productid,p.productname,p.productno,p.marketprice,p.memberprice,p.weight,                        
d.price as pmtprice,c.quantity,g.weight*c.quantity as subweight,
d.price*c.quantity as SubMoney,--小计金额      
(g.memberprice-d.price)*c.quantity as LessMoney,--优惠金额                          
--pmtname,ruleid,basictype,subtype,
'套装商品' as remark,g.GoodsID,p.IsDlvUnit,p.DlvUnit,p.MiniBuyNum,d.Score*c.quantity,                        
0 as StowageID,1 as IsOfferInvoice,
--RecordID,ProductSpecs,pmtid,
0 as IsDiscount,0 as UseScore,0,p.SupplierID,p.ImgFolder,p.ProductImg,c.suitid,d.sort                              
from  suitdetail d(nolock),suitscart c(nolock),product p(nolock),goods g(nolock)
where c.cartid=@cartid and c.suitid=d.suitid and d.productid=p.productid and d.goodsid=g.goodsid

--6.2礼品购物车表 
--description:统计原先换购的礼品和积分兑换的礼品放入#oldgift，清空礼品购物车中非换购和积分兑换的礼品，

--6.2.1保证原先选择的礼品不会被删除                        
select  c.*                         
into  #oldgift                        
from giftscart c(nolock),#gift t(nolock)                         
where                         
(isnull(c.ruleid,0)=0 and c.UseScore>0 and c.cartid=@cartid)--积分兑换的礼品                        
or
(c.addtime>getdate()-1                        
and c.productid=t.productid                         
and c.giftnumber=t.giftnumber                        
and c.giftnumber>0--礼品数量为0的不能保留                        
and c.isSystemAdd=0--礼品非系统自动添加                        
and c.cartid=@cartid)

--select * from #oldgift
                         
-- 商品数量进行了修改，需要删除变化礼品信息                    
delete g                         
from giftscart g(nolock)                        
where                         
1=1                        
and g.RuleID not in(            
select o.ruleid                          
from  #oldgift o(nolock) 
where cartid=@cartid                        
)                                                
and g.cartid=@cartid  

--6.2.2 单个礼品规则，且价格为0的，自动添加到礼品表中。                        
--选出规则中只有单个礼品，且价格为0的规则,且上次保留的礼品信息                      
select g.ruleid                        
into #SinpleGift                        
from #gift g                         
where                         
1=1                         
and g.ruleid not in(                         
select o.ruleid from  #oldgift o(nolock) where cartid=@cartid                        
)
--and g.giftnumber>0 --礼品数量大于0的才添加                       
and g.pmtprice=0                        
group by g.ruleid                        
having count(g.ruleid)=1

--select * from #gift
--select * from #SinpleGift

--6.2.3 系统自动添加的礼品信息                                     
insert into giftscart(                            
cartid,productid,productno,marketprice,memberprice,weight                            
,pmtprice,giftnumber,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,giftremark                         
,productname,isSystemAdd,pmtid,UseScore,supplierid,goodsid,rulename,ImgFolder,ProductImg                          
)                            
select @cartid,c.productid,p.productno,c.marketprice,c.memberprice,p.weight                            
,c.pmtprice,giftnumber,giftnumber*p.weight,c.pmtprice*giftnumber submoney,(c.memberprice-c.pmtprice)*giftnumber lessmoney, --有疑惑                          
pmtname,c.ruleid,basictype,subtype,giftremark                        
,p.productname ,1 isSystemAdd,c.pmtid,0,--非积分兑换，使用积分为0 
c.supplierid,c.goodsid,c.rulename,p.imgfolder,p.productimg                             
from  #gift c(nolock) ,#SinpleGift s(nolock),product p(nolock)                        
where 
c.ruleid=s.ruleid and c.productid=p.productid  
 
--积分兑换的礼品
insert into giftscart(                            
cartid,productid,productno,marketprice,memberprice,weight                            
,pmtprice,giftnumber,subweight,submoney,lessmoney,giftremark                         
,productname,isSystemAdd,UseScore,supplierid,goodsid,ImgFolder,ProductImg                         
)
select @cartid,s.productid,p.productno,p.marketprice,p.memberprice,p.weight                          
,0 pmtprice,s.quantity,s.quantity*p.weight,0 submoney,p.memberprice*s.quantity lessmoney,'积分兑换' giftremark                        
,p.productname ,0 isSystemAdd,s.giftscore,p.supplierid,s.goodsid,p.imgfolder,p.productimg                               
from  shoppingcart s(nolock),product p(nolock)                    
where 
s.cartid=@cartid and s.ptype=2 and s.productid=p.productid
                     
                        
--6.2.4 删除系统自动添加的礼品信息                       
delete c                        
from  #gift c(nolock) ,#SinpleGift s(nolock)                        
where c.ruleid=s.ruleid   

--6.2.5 可选礼品信息表                       
delete from GiftsCart_temp where cartid=@cartid                        
insert into GiftsCart_temp(                            
cartid,productid,productno,marketprice,memberprice                            
,pmtprice,giftnumber,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,giftremark,productname                  
)                         
select @cartid,p.productid,p.productno,c.marketprice,c.memberprice                            
,pmtprice,c.giftnumber,c.memberprice*giftnumber submoney,c.pmtprice*giftnumber lessmoney,                            
c.pmtname,c.ruleid,basictype,subtype,giftremark,p.productname              
from  #gift c(nolock),product p(nolock)                        
where c.productid=p.productid

                           
                     
--7 购物车信息                        
--7.1显示购物车商品信息      
print('output->7.1显示购物车商品信息  ')                          
select '' as 购物车商品信息,
c.* from                             
--#cart c(nolock)
goodscart c(nolock)
where cartid=@cartid 
--and quantity>0
order by sort desc,recordid 
                           
--7.2显示购物车礼品信息
print('output->7.2显示购物车礼品信息')                                                      
select '' as 购物车礼品信息,
c.*                       
from giftscart c(nolock)                
where cartid=@cartid                     
                       
--7.3需要用户自己选择的礼品，需要会员自己决定手工将礼品加入到礼品表中 
if coalesce(@memberid, -1)=-1                         
begin  
--未登录会员不显示礼品信息 
print('output->7.3未登录会员不显示可选择礼品信息')                                             
select top 0 c.* ,r.rulename from giftscart_temp c,pmtrule r(nolock) where cartid=@cartid and c.ruleid = r.ruleid                                             
end
                            
else                             
begin 
--已登录会员显示礼品信息 
print('output->7.3已登录会员显示可选择礼品信息')                   
select '' as 可选礼品信息,
c.* ,r.rulename from giftscart_temp c,pmtrule r(nolock) where cartid=@cartid and c.ruleid = r.ruleid                                      
end  

--7.4商家集合
print('output->7.5商家集合')
--订单商家分组信息                         
--商品品种数、商品总数量、总金额、总获得积分、总使用积分、总的积分抵扣金额、总优惠的金额
select cartid,count(productid) goodsnumber,sum(quantity) totalnumber ,sum(subweight) totalweight,sum(submoney-scoremoney) totalmoney ,sum(score) totalscore,sum(usescore) usedscore,sum(scoremoney) totalscoremoney,sum(LessMoney) totallessmoney,supplierid                        
into #ordermessage                  
from                        
(                        
select cartid,productid,goodsid,quantity,subweight,submoney,Score,UseScore,ScoreMoney,LessMoney,supplierid                         
from goodscart g(nolock)                        
where cartid=@cartid                        
union                        
select cartid,productid,goodsid,giftnumber,subweight,submoney, 0 Score,UseScore,0 ScoreMoney,LessMoney,supplierid                         
from giftscart g(nolock)                        
where cartid=@cartid                        
) as t                        
group by cartid,supplierid                        
--分商家订单商品品种数、商品总数量、总金额、总积分、总优惠的金额 
print('output->分商家订单商品品种数、商品总数量、总金额、总获得积分、总使用积分、总的积分抵扣金额、总优惠的金额')                     
select '' as '购物车商家汇总信息',
o.*,s.suppliername                
from #ordermessage o(nolock),supplier s(nolock)
where o.supplierid=s.supplierid

--7.5订单信息 
--订单商品品种数、商品总数量、总金额、总积分、总优惠的金额 
print('output->7.5订单商品品种数、商品总数量、总金额、总获得积分、总使用积分、总的积分抵扣金额、总优惠的金额')                     
select '' as '购物车汇总信息',
cartid,sum(goodsnumber) goodsnumber,sum(totalnumber) totalnumber ,sum(totalweight) totalweight,sum(totalmoney) totalmoney ,sum(totalscore) totalscore,sum(usedscore) usedscore,sum(totalscoremoney) totalscoremoney,sum(totallessmoney) totallessmoney                                          
from #ordermessage o(nolock) 
group by o.cartid

--7.6显示套装信息
print('output->7.6显示套装信息')   
select '' as 套装信息,
*,(MarketPrice-MemberPrice) as LessMoney 
from suitscart 
where cartid=@cartid 

--7.7显示单品返券
print('output->7.7显示单品返券')   
select '单品返券' as 单品返券,c.couponname,c.number as number,g.productid,g.goodsid,t.supplierid
from #cart t,pmtrule r(nolock),pmtgoods g(nolock),pmtcoupons c(nolock)
where t.productid=g.productid and g.ruleid=r.ruleid and r.basictype='goods' and r.subtype='coupon' and getdate() between BeginTime and EndTime and c.ruleid=r.ruleid and r.supplierid=t.supplierid


--7.8订单金额优惠信息,暂时不做                                        
print('output->7.8订单金额优惠信息,暂时不做')                            
select top 1 '订单优惠金额暂时先不做' as 订单优惠金额暂时先不做,
* from #orderpromotion



/*
print('debug->商品购物车') 
select '商品购物车' as debug商品购物车,
* from goodscart
print('debug->礼品购物车')                           
select '礼品购物车' as debug礼品购物车,
* from giftscart                    
*/
                     
--declare @shipfeer money,@CouponValue money,
--declare @ordermoney money                      
--select @shipfeer=0                  
--select @CouponValue=0                      
--select @ordermoney=(select top 1 totalmoney from #ordermessage)                      
                      
/*
print('--10.5运费  ')                                            
delete from ShipCart where cartid=@cartid                      
insert into ShipCart(cartid,shipfeer,memberid)                       
values(@cartid,@shipfeer,@memberid)                      
                    
select shipfeer=@shipfeer                      
print('--10.6优惠券')                      
select   CouponValue ,CouponName                      
into #CouponCart                      
from CouponCart c(nolock),CouponDetail d(nolock)                      
where c.CartID=@CartID                      
and d.CouponID=c.CouponID                   
and c.CouponID in (select CouponID from goodscart(nolock) where cartid=@cartid)                    
select * from #CouponCart                      
select @CouponValue=(select  isnull(sum(CouponValue),0)  from #CouponCart)                      
*/
              
--print('output->应付款')                      
--select neepaymoney=@ordermoney+@shipfeer-@CouponValue                      
--select neepaymoney=@ordermoney 

/*                   
print('10.8参与活动或者是其它信息')                     
if object_id('tempdb.dbo.#activelist_temp') is not null                    
begin                    
drop table #activelist_temp                    
end                    
create table #activelist_temp                    
(                    
activename varchar(1000) default '',                    
tipmessage varchar(200) default ''                    
)                    
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;">满50元可使用5元优惠券（促销商品除外）</span>',tipmessage='满50元可使用5元优惠券'                     
                    
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;">满100元可使用10元优惠券（促销商品除外）</span>',tipmessage='满100元可使用10元优惠券'                     
                
                
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;"><a href="products/product-1100530.html">5L金龙鱼花生浓香调和油特价每人限购1瓶</a></span>',tipmessage='5L金龙鱼花生浓香调和油特价每人限购1瓶,数量有限'      
where getdate() between getdate()-5 and  '2010-12-01'                 
                
select  *  from #activelist_temp  
*/

END
































GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Cart_Update]    脚本日期: 04/09/2012 18:26:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Hakkas>
-- Create date: <2011-04-21>
-- Description:	<更新购物车>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Cart_Update]
@cartid varchar(36),--购物车ID
@qty int,--购买数量
@pid int,--商品ID
@gid int,--货品ID
@specs varchar(200),--商品规格信息
@ptype int,--类型:1商品；2礼品
@sid int, --商品所属商家ID
@pnum int out,--返回购物车商品总数
@iserrorflag int out,--错误标志
@errormsg varchar(200) out--错误信息描述
AS
BEGIN
	select @iserrorflag=0,@errormsg=''
	--判断是否已经有相同的商品在同一购物车内
    if Exists(SELECT RecordID FROM ShoppingCart WHERE CartID=@cartid and ProductID=@pid and GoodsID=@gid)
		-- 购物车里已有相同记录，做数量更新
		UPDATE ShoppingCart SET Quantity = Quantity+@qty WHERE CartID=@cartid and ProductID=@pid and GoodsID=@gid
	else
		begin
		--购物车里还没有该商品记录，做插入
		INSERT INTO ShoppingCart 
		(CartID,Quantity,ProductID,AddTime,ProductSpecs,GoodsID,Ptype,SupplierID) 
		VALUES
		(@cartID,@qty,@pid,getdate(),@specs,@gid,@ptype,@sid)
		end
	--返回购物车商品数量
	select @pnum=sum(Quantity) from ShoppingCart where cartid=@cartid and ptype=1 group by cartid
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CartItem_Add]    脚本日期: 04/09/2012 18:26:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Hakkas>
-- Create date: <2011-04-21>
-- Description:	<添加商品到购物车>
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110823                              
content:                                
1.增加套装购买功能                                
*/
/*
debug:
declare @pids varchar(4000),@gids varchar(4000),@qtys varchar(4000),@ptype int,@errorflag int,@errormsg varchar(200)
select @pids='586,586,580'
select @gids='672,673,664'
select @qtys='1,1,1'
select @ptype=1
exec XpProc_CartItem_Add '41272f23-5773-4733-9e3f-a4009b4415c2',2,@pids,@gids,@qtys,@ptype,@errorflag out,@errormsg out
select @errorflag,@errormsg
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_CartItem_Add]
@cartid varchar(36),--购物车ID
@memberid int,--会员ID
@pids varchar(4000),--商品ID
@gids varchar(4000),--货品ID
@qtys varchar(4000),--购买数量
@ptype int,--类型:1商品；2礼品
@errorflag int out,--错误标志
@errormsg varchar(200) out--错误信息描述
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
select * into #p from SplitToTable_Func(@pids,',')
select * into #g from SplitToTable_Func(@gids,',')
select * into #q from SplitToTable_Func(@qtys,',')

select top 0 cartid=@cartid,0 as quantity,0 as productid,0 as goodsid,1 as ptype,0 as giftscore,0 as supplierid
into #t
--from product(nolock)

if @ptype=1
insert into #t
select cartid=@cartid,isnull(q.value,1) as Quantity,p.value as ProductID,g.value as GoodsID,ptype=@ptype,0 as giftscore,isnull(pt.supplierid,0) as supplierid
from #p p
left join #g g on p.id=g.id
left join product pt(nolock) on p.value=pt.productid
left join #q q on p.id=q.id

else if @ptype=2
insert into #t
select cartid=@cartid,q.value as Quantity,p.value as ProductID,g.value as GoodsID,ptype=@ptype,gt.score as giftscore,pt.supplierid
from #p p,#g g,#q q,product pt(nolock)
left join gift gt(nolock) on pt.productid=gt.productid
where p.value=pt.productid and p.id=g.id and p.id=q.id

else if @ptype=3
insert into #t
select cartid=@cartid,q.value as Quantity,p.value as ProductID,g.value as GoodsID,ptype=@ptype,0 as giftscore,s.supplierid
from #p p,#g g,#q q,suit s(nolock)
where p.value=s.suitid and p.id=g.id and p.id=q.id

else
begin
select @errorflag=1,@errormsg='参数错误'
return
end

-- 更新购物车里已有相同商品的数量
update s set s.Quantity = s.Quantity+t.Quantity from shoppingcart s(nolock), #t t where s.cartid=t.cartid and s.productid=t.productid and s.goodsid=t.goodsid and s.ptype=t.ptype
--插入购物车里还没有的商品记录
insert into ShoppingCart (CartID,Quantity,ProductID,GoodsID,Ptype,GiftScore,SupplierID) select * from #t where #t.productid not in(SELECT ProductID FROM ShoppingCart WHERE CartID=#t.cartid and ProductID=#t.productid and GoodsID=#t.goodsid and ptype=#t.ptype)
exec XpProc_Cart_Look @cartid,@memberid,@errorflag out ,@errormsg out
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
	
END












GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CartItem_Add_20110823]    脚本日期: 04/09/2012 18:26:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Hakkas>
-- Create date: <2011-04-21>
-- Description:	<添加商品到购物车>
/*
debug:
declare @pids varchar(4000),@gids varchar(4000),@qtys varchar(4000),@ptype int,@errorflag int,@errormsg varchar(200)
select @pids='586,586,580'
select @gids='672,673,664'
select @qtys='1,1,1'
select @ptype=1
exec XpProc_CartItem_Add '41272f23-5773-4733-9e3f-a4009b4415c2',2,@pids,@gids,@qtys,@ptype,@errorflag out,@errormsg out
select @errorflag,@errormsg
*/
-- =============================================
create PROCEDURE [dbo].[XpProc_CartItem_Add_20110823]
@cartid varchar(36),--购物车ID
@memberid int,--会员ID
@pids varchar(4000),--商品ID
@gids varchar(4000),--货品ID
@qtys varchar(4000),--购买数量
@ptype int,--类型:1商品；2礼品
@errorflag int out,--错误标志
@errormsg varchar(200) out--错误信息描述
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
select * into #p from dbo.SplitToTable_Func(@pids,',')
select * into #g from dbo.SplitToTable_Func(@gids,',')
select * into #q from dbo.SplitToTable_Func(@qtys,',')

select cartid=@cartid,q.value as Quantity,p.value as ProductID,g.value as GoodsID,ptype=@ptype,case when @ptype=1 then 0 else gt.score end as giftscore,pt.supplierid
into #t 
from #p p,#g g,#q q,product pt(nolock)
left join gift gt(nolock) on pt.productid=gt.productid
where p.value=pt.productid and p.id=g.id and p.id=q.id
-- 更新购物车里已有相同商品的数量
update s set s.Quantity = s.Quantity+t.Quantity from shoppingcart s(nolock), #t t where s.cartid=t.cartid and s.productid=t.productid and s.goodsid=t.goodsid
--插入购物车里还没有的商品记录
insert into ShoppingCart (CartID,Quantity,ProductID,GoodsID,Ptype,GiftScore,SupplierID) select * from #t where #t.productid not in(SELECT ProductID FROM ShoppingCart WHERE CartID=#t.cartid and ProductID=#t.productid and GoodsID=#t.goodsid)
exec XpProc_Cart_Look @cartid,@memberid,@errorflag out ,@errormsg out
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
	
END










GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CartPdtQty_Update]    脚本日期: 04/09/2012 18:26:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Hakkas>
-- Create date: <2010-03-12>
-- Description:	<更新购物车商品数量>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_CartPdtQty_Update] 
@cartid nvarchar(50),--购物车ID
@memberid int=-1,--会员ID
@productid int=0,--商品ID
@goodsid int=0,--货品ID
@qty int=1,--数量
@ptype int=1,--1商品,2礼品
@scorerate decimal(18,2)=0.01,--积分兑换货币比率
@iserrorflag int =0 out,--错误标志
@errormsg varchar(200)='' out--错误信息描述
AS
BEGIN
select @iserrorflag=0,@errormsg=''
-- =============================================
--更新购物车商品数量开始
--数量为0为移除商品
if @qty=0
begin
DELETE FROM ShoppingCart WHERE CartID=@cartid and productid=@productid and GoodsID=@goodsid and Ptype = @ptype
end

else
begin
--数量不为0为修改购买的商品数量
--获取商品及货品的基本信息
declare @IsDlvUnit int,@dlvUnit int,@isNeedStorage int,@storage int
select @IsDlvUnit=IsDlvUnit,@dlvUnit=dlvUnit,@isNeedStorage=isnull(IsNeedStorage,1),@storage=g.Storage 
from product p,goods g
where 
p.productid=@productid and GoodsID=@goodsid and g.productid=@productid

if @IsDlvUnit=1
select @qty=@qty*@dlvUnit

if (@isNeedStorage=1 and @storage<@qty)
begin
--商品需要库存且库存小于购买数量，提示库存不足
select @iserrorflag=1,@errormsg='nostorage'
return;
end
else
begin
--更新购物车商品数量
UPDATE ShoppingCart SET	Quantity=@qty WHERE CartID=@cartid and productid=@productid and goodsid=@goodsid and ptype=@ptype
end

end
--更新购物车结束
-- =============================================

exec XpProc_Cart_Look @cartid,@memberid,@iserrorflag out ,@errormsg out

END














GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CartShipPrice_Get]    脚本日期: 04/09/2012 18:26:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas>
-- Create date: <2010-10-01>
-- Description:	<计算订单配送费用>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_CartShipPrice_Get]
@cartid varchar(36),--购物车ID
@payType int,--支付方式
@subAreaID int,--收货地址市级ID
@shippingID int,--配送方式ID
@weight decimal(18,2),--商品总重量
@pmtPdtPrice money,--优惠后的商品总价
@mid int,--会员ID
@sid int,--商家ID
@shipPrice money out--配送费用
AS
BEGIN
if(@payType=6)--到自提点提货,运费为0
begin
	select @shipPrice=0
end
else--物流配送
begin
	--先判断时候符合免运费条件
	declare @freeType int,@leastMoney decimal(18,2)
	select top 1 @freeType=FreeType,@leastMoney=LeastMoney from ShippingFree(nolock) where SupplierID=@sid
	select @freeType=isnull(@freeType,0),@leastMoney=isnull(@leastMoney,99999999)
	if(@freeType=0)--不免运费，要通过运费公式计算运费
	begin
		exec dbo.xpproc_shipprice_get @subAreaID,@shippingID,@weight,@sid,@shipPrice out
	end
	else if(@freeType=1)--所有地区统一最低免运费消费金额
	begin
		if(@pmtPdtPrice>@leastMoney)--商品总额大于最低消费金额
		begin
			--免运费
			select @shipPrice=0
		end
		else
		begin
			--计算运费
			exec dbo.xpproc_shipprice_get @subAreaID,@shippingID,@weight,@sid,@shipPrice out
		end
	end
	else--分地区设定最低免运费消费金额
	begin
		select @leastMoney=Least from ShippingArea(nolock) where ShippingAreaID=@subAreaID--获取对应地区的最低免运费消费金额
		if(@pmtPdtPrice>=@leastMoney)--商品总额大于最低消费金额
		begin
			--免运费
			select @shipPrice=0
		end
		else
		begin
			--计算运费
			exec dbo.xpproc_shipprice_get @subAreaID,@shippingID,@weight,@sid,@shipPrice out
		end
	end
end
--记录配送价格到购物车配送价格表ShipCart
insert into ShipCart(cartid,shipprice,memberid,supplierid,remark) values (@cartid,@shipPrice,@mid,@sid,'')
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CartStore_Look]    脚本日期: 04/09/2012 18:26:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Hakkas>
-- Create date: <2010-03-12>
-- Description:	<查看商家购物车信息>
/*
引用该存储过程的存储过程：
1、XpProc_Checkout_Init
*/

/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110725                              
content:                                
1.添加输出参数@banknum记录购物车是否包含银行促销商品                                
*/

/*debug:
declare @pdtprice money,@weight decimal(18,2),@banknum int
exec XpProc_CartStore_Look '41272f23-5773-4733-9e3f-a4009b4415c2',2,0,@pdtprice out,@weight out,@banknum out
select @pdtprice,@weight
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_CartStore_Look] 
@cartid nvarchar(50),--购物车ID
@memberid int=-1,--会员ID
@sid int =0,--商品所属商家ID
@pdtPrice money out,--商品金额
@weight decimal(18,2) out,--商品重量
@banknum int out--银行活动商品数量
AS
BEGIN
declare @scorerate decimal(18,2)--积分兑换货币比率
select @scorerate=0.01

--获取会员对应会员组享受的折扣
declare @groupid int,--会员组ID
@groupname nvarchar(20),--会员组名称
@discount decimal(18,2)--会员组折扣

select @groupid=0
select @groupid=groupid,@groupname=mg.groupname,@discount=cast(mg.discount/100.00 as decimal(18,2)) from member m,membergroup mg where m.groupid=mg.MemberGroupID and m.memberid=@memberid
--print('获取会员对应会员组享受的折扣')
--select @groupid as '会员组ID',@discount as '会员组折扣'


--declare @cartid nvarchar(100)
--select @cartid='10a2fd6e-e9c4-4142-a9d8-41cf9c763f6c'

--0. 套餐信息
delete from suitscart where cartid=@cartid and supplierid=@sid

insert into suitscart(cartid,suitid,RecordID,suitname,marketprice,memberprice,quantity,score)
select @cartid,suitid,c.RecordID,suitname,oldprice,price,c.quantity,0 score
from shoppingcart c(nolock),suit s(nolock)
where c.cartid=@cartid and c.ptype=3 and c.productid=s.suitid and c.supplierid=@sid


--1.购物车信息
select       
p.productid,p.productno,isnull(gg.goodsname,p.productname) as productname,gg.marketprice,gg.memberprice,gg.weight,      
c.CartID,c.quantity,p.ImgFolder,p.ProductImg,
gg.weight*c.quantity subweight,      
isnull(g.pmtprice,gg.memberprice) as pmtprice,
--isnull(g.pmtprice,case when @discount<>'100' and p.IsDiscount=1 then gg.memberprice*cast(@discount/100.00 as decimal(18,2)) else null end) pmtprice,--优惠单价
isnull(g.pmtprice,gg.memberprice)*c.quantity SubMoney,--小计金额      
(gg.memberprice-isnull(g.pmtprice,gg.memberprice))*c.quantity LessMoney,--优惠金额      
 g.pmtname,g.RuleID ,g.RuleName,g.BasicType,g.SubType,      
convert(varchar(200),'') remark, 
gg.GoodsID,p.IsDiscount,1 IsDlvUnit,1 DlvUnit,MiniBuyNum,gg.Score,0 usescore,0 StowageID,1 IsOfferInvoice, 
RecordID,ProductSpecs  
,g.pmtid--活动ID
,p.supplierid,g.bankno
into #cart       
from
ShoppingCart c(nolock),goods gg(nolock),product p(nolock)     
left join PmtGoodsList g
on( p.productid=g.productid and g.BasicType='goods' and g.SubType in('discount','specialprice','limittime')--一个商品只能作一个特价或折扣
and charindex(','+convert(nvarchar(10),@groupid)+',',','+g.GroupIDs+',')>0--允许参与优惠活动的会员组才可以享受优惠
and g.balance>0
)       
where
--c.supplierid=@sid--目前购物车表的supplierid都是0，有问题
p.supplierid=@sid --只查看对应商家的购物车商品
and c.productid=p.productid
and gg.goodsid=c.goodsid--增加多维规格功能  
and p.productid=gg.productid      
and c.quantity>0
and c.ptype=1--商品      
and c.cartid=@cartid

update #cart set pmtprice=memberprice*@discount,submoney=submoney*@discount,lessmoney=(memberprice-memberprice*@discount)*quantity,rulename=@groupname+':'+left(convert(varchar(10),@discount*10),3)+'折' where isnull(ruleid,0)=0 and IsDiscount=1 and @discount<>'1.00'
--2.商品购买数量控制 
select b.*      
into #MemberBookProduct      
from MemberBookPmtGoods b(nolock),#cart c(nolock)      
where 
b.RuleID=c.RuleID and c.productid=b.productid 

--2.1购买总数量限制      
select p.RuleID,p.productid,g.PmtNumber maxgoodsnumber,sum(p.quantity) goodsnumber      
into #MemberBookProduct_a--购买总数统计表      
from #MemberBookProduct p(nolock),PmtGoods g(nolock)      
where g.ruleid=p.ruleid      
and g.productid=p.productid      
and g.PmtNumber>0--限制数量
group by p.RuleID,p.productid,g.PmtNumber      
having sum(p.quantity)>=g.PmtNumber      
      
--2.2会员购买数量限制      
select p.ruleid,p.productid,memberid ,g.LimitedNumber maxmembernumber,sum(quantity) membernumber      
into #MemberBookProduct_b--个人购买统计表      
from #MemberBookProduct p(nolock) ,PmtGoods g(nolock)      
where       
g.ruleid=p.ruleid      
and g.productid=p.productid      
and g.LimitedNumber>0--限制数量      
and memberid=@memberid      
group by  p.ruleid,p.productid,memberid ,g.LimitedNumber        
having sum(p.quantity)>=g.LimitedNumber      
      
--2.3汇总      
--2.3.1      
update c set c.quantity=0,SubMoney=0,LessMoney=0, remark='此商品已经抢购完,<span style="color:Green;">谢谢您的支持，请在下次购买</span>'                
from #cart c,#MemberBookProduct_a a(nolock)                            
where                     
c.ruleid=a.ruleid                            
and c.productid=a.productid      
      
--2.3.2      
update c set c.quantity=0,SubMoney=0,LessMoney=0, remark='您已超过此商品最大购买抢购量:'+convert(varchar(8),a.maxmembernumber)+',<span style="color:Green;">谢谢您的支持，请在下次购买</span>'              
from #cart c,#MemberBookProduct_b a(nolock)                            
where                            
c.ruleid=a.ruleid                            
and c.productid=a.productid         
      
--2.3.3     
update c set c.quantity=0,SubMoney=0,LessMoney=0, remark='您已超过此商品最大购买抢购量:'+convert(varchar(8),a.LimitedNumber)+',<span style="color:Green;">请修改数量</span>'              
from #cart c,PmtGoods a(nolock)                            
where                            
c.ruleid=a.ruleid                            
and c.productid=a.productid                            
and ((c.quantity> a.PmtNumber and  a.PmtNumber>0)                             
or c.quantity>a.LimitedNumber and a.LimitedNumber>0) 
    

--3.1购物车汇总，获取参与促销活动汇总信息                        
--drop table  #orderinfo                 
select l.ruleid,sum(SubMoney) totalprice,sum(quantity) totalnumber                            
into #orderinfo                            
from #cart c(nolock),PmtGoodsList l(nolock)                            
where                         
1=1                        
and                         
c.productid=l.productid        
and c.goodsid=l.goodsid                      
and l.SubType='gift'   --礼品换购信息                          
group by l.ruleid    
                          
--3.2获取赠品商品信息                        
if object_id('tempdb.dbo.#gift') is not null                            
begin       
drop table #gift                            
end                                
select  floor(                        
case when isautoAdded=1 then                            
case when r.BasicType='orders' then o.totalprice                            
when r.BasicType='goods' then o.totalnumber end/minvalue  --订单满额规格可能有问题
else 1 end) giftnumber,--可获礼品数量                            
convert(varchar(200),' ') giftremark, r.BasicType,g.SubType,                       
g.ID,g.PmtName,g.RuleID,g.RuleNo,                        
g.RuleName,g.productid,g.goodsid,g.productname,                        
g.categoryid,g.brandid,g.brandname,g.usescore,g.score,                        
g.marketprice,g.memberprice,g.PmtPrice,g.stowageid,                        
g.PmtNumber,g.LimitedNumber,g.IsLimited,g.maxnumber,g.isselected,                        
g.gifttype,g.groupname,g.addtime,g.status,                        
--g.adduser,g.deltime,g.deluser,
g.remark,
r.PmtID,g.supplierid                     
into #gift                             
from #orderinfo o(nolock),PmtRule r(nolock),PmtGifts g(nolock),Product p(nolock)   -----------------------------这里为什么要联商品表product????????????                         
where                             
o.ruleid=r.ruleid                          
and p.productid=g.productid                          
and g.ruleid=r.ruleid                            
and r.SubType='gift'                            
and minvalue                            
<=case when r.BasicType='orders' then o.totalprice               
when r.BasicType='goods' then o.totalnumber end--起始条件                            
and (  maxvalue=0 or  isautoAdded=1 or                          
convert(money,maxvalue)>case when r.BasicType='orders' then o.totalprice                            
when r.BasicType='goods' then o.totalnumber end--最大条件                            
)

--4.礼品数量限制                    
if object_id('tempdb.dbo.#MemberBookGift') is not null                            
begin                            
drop table #MemberBookGift                            
end                            
select b.*                            
into #MemberBookGift                            
from MemberBookPmtGoods b(nolock),#gift c(nolock)                            
where b.RuleID=c.RuleID                            
and c.productid=b.productid                            
                            
--4.1总数限制                           
if object_id('tempdb.dbo.#MemberBookGift_a') is not null                            
begin                            
drop table #MemberBookGift_a                            
end           
select p.RuleID,p.productid,l.PmtNumber,sum(p.quantity) SaleNumber                            
into #MemberBookGift_a                            
from #MemberBookGift p(nolock),PmtGifts l(nolock)                            
where l.RuleID=p.RuleID                            
and l.productid=p.productid                            
and l.PmtNumber>0--有限制数量                            
group by p.RuleID,p.productid,l.PmtNumber                            
having sum(p.quantity)>=l.PmtNumber                      
                            
--4.2个人数量限制                           
if object_id('tempdb.dbo.#MemberBookGift_b') is not null                            
begin                            
drop table #MemberBookGift_b                            
end                            
select p.RuleID,p.productid,memberid,l.LimitedNumber,sum(quantity) PersonalNumber                            
into #MemberBookGift_b                            
from #MemberBookGift p(nolock) ,PmtGifts l(nolock)                            
where                             
l.RuleID=p.RuleID                            
and l.productid=p.productid                            
and l.LimitedNumber>0--有限制个人购买数量                            
and memberid=@memberid                            
group by  p.RuleID,p.productid,memberid,l.LimitedNumber                              
having sum(p.quantity)>=l.LimitedNumber 
                           
--4.3 赠品信息汇总 
--4.3.1 赠品信息,此礼品已经送完完                          
update c set giftnumber=0,giftremark='此礼品已经送完'                            
from #gift c,#MemberBookGift_a a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                        
--4.3.2 赠品信息,你已超过此礼品的最大量                        
update c set giftnumber=0,giftremark='你已超过此礼品的最大量!'                            
from #gift c,#MemberBookGift_b a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                            
--4.3.3 赠品信息,最后一次仍送出                          
update c set giftnumber=a.LimitedNumber,giftremark='最后一次仍送出!'                            
from #gift c,PmtGoods a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                            
and ((c.giftnumber> a.PmtNumber and  a.PmtNumber>0)                             
or c.giftnumber>a.LimitedNumber and a.LimitedNumber>0) 

--4.4 赠品库存控制    
update c set giftnumber=0,giftremark='很抱歉，此赠品已经送完!'                            
from #gift c,goods g(nolock)                            
where            
c.goodsid=g.goodsid    
and g.Storage<=0

--5 订单总金额优惠信息                          
select top 0  TotalMoney=0, LessMoney=0,ruleid=' ' ,rulename=' ' ,moneyremark=' '                           
into #orderpromotion

--6 显示信息

--6.1 商品购物车表                            
delete from goodscart where cartid=@cartid and supplierid=@sid                                                    
insert into goodscart(                     
cartid,productid,productname,productno,marketprice,memberprice,weight,                          
pmtprice,quantity,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,remark,                        
GoodsID, IsDlvUnit, DlvUnit,MiniBuyNum,Score,                        
StowageID,IsOfferInvoice,RecordID,ProductSpecs                      
,pmtid,IsDiscount,UseScore,ScoreMoney,SupplierID,RuleName,ImgFolder,ProductImg,suitid                       
)                            
select @cartid,productid,productname,productno,marketprice,memberprice,weight,                        
pmtprice,quantity,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,remark,                        
GoodsID, IsDlvUnit, DlvUnit,MiniBuyNum,Score*quantity,                        
StowageID,IsOfferInvoice,RecordID,ProductSpecs                        
,pmtid,IsDiscount,UseScore,UseScore*@scorerate,SupplierID,RuleName,ImgFolder,ProductImg,0 as suitid                             
from  #cart c(nolock)

--6.1.1添加套装商品
insert into goodscart(                     
cartid,productid,productname,productno,marketprice,memberprice,weight,                          
pmtprice,quantity,subweight,submoney,lessmoney,                            
--pmtname,ruleid,basictype,subtype,
remark,GoodsID,IsDlvUnit, DlvUnit,MiniBuyNum,Score,                        
StowageID,IsOfferInvoice,
--RecordID,ProductSpecs,pmtid,
IsDiscount,UseScore,ScoreMoney,SupplierID,ImgFolder,ProductImg,suitid,sort                        
)                            
select @cartid,p.productid,p.productname,p.productno,p.marketprice,p.memberprice,p.weight,                        
d.price as pmtprice,c.quantity,g.weight*c.quantity as subweight,
d.price*c.quantity as SubMoney,--小计金额      
(g.memberprice-d.price)*c.quantity as LessMoney,--优惠金额                          
--pmtname,ruleid,basictype,subtype,
'套装商品' as remark,g.GoodsID,p.IsDlvUnit,p.DlvUnit,p.MiniBuyNum,d.Score*c.quantity,                        
0 as StowageID,1 as IsOfferInvoice,
--RecordID,ProductSpecs,pmtid,
0 as IsDiscount,0 as UseScore,0,p.SupplierID,p.ImgFolder,p.ProductImg,c.suitid,d.sort                              
from  suitdetail d(nolock),suitscart c(nolock),product p(nolock),goods g(nolock)
where c.cartid=@cartid and c.supplierid=@sid and c.suitid=d.suitid and d.productid=p.productid and d.goodsid=g.goodsid

--6.2礼品购物车表 
--description:统计原先换购的礼品和积分兑换的礼品放入#oldgift，清空礼品购物车中非换购和积分兑换的礼品，

--6.2.1保证原先选择的礼品不会被删除                        
select  c.*                         
into  #oldgift                        
from giftscart c(nolock),#gift t(nolock)                         
where                         
(isnull(c.ruleid,0)=0 and c.UseScore>0 and c.cartid=@cartid)--积分兑换的礼品                        
or
(c.addtime>getdate()-1                        
and c.productid=t.productid                         
and c.giftnumber=t.giftnumber                        
and c.giftnumber>0--礼品数量为0的不能保留                        
and c.isSystemAdd=0--礼品非系统自动添加                        
and c.cartid=@cartid)
                         
-- 商品数量进行了修改，需要删除变化礼品信息                    
delete g                         
from giftscart g(nolock)                        
where                         
1=1                        
and g.RuleID not in(            
select o.ruleid                          
from  #oldgift o(nolock) 
where cartid=@cartid                        
)                                                
and g.cartid=@cartid  

--6.2.2 单个礼品规则，且价格为0的，自动添加到礼品表中。                        
--选出规则中只有单个礼品，且价格为0的规则,且上次保留的礼品信息                      
select g.ruleid                        
into #SinpleGift                        
from #gift g                         
where                         
1=1                         
and g.ruleid not in(                         
select o.ruleid                         
from  #oldgift o(nolock) where cartid=@cartid                        
)  
--and g.giftnumber>0                      
and g.pmtprice=0                        
group by g.ruleid                        
having count(g.ruleid)=1

--6.2.3 系统自动添加的礼品信息                                     
insert into giftscart(                            
cartid,productid,productno,marketprice,memberprice,weight                            
,pmtprice,giftnumber,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,giftremark                         
,productname,isSystemAdd,pmtid,UseScore,supplierid,goodsid,rulename,ImgFolder,ProductImg                          
)                            
select @cartid,c.productid,p.productno,c.marketprice,c.memberprice,p.weight                           
,c.pmtprice,giftnumber,giftnumber*p.weight,c.pmtprice*giftnumber submoney,(c.memberprice-c.pmtprice)*giftnumber lessmoney, --有疑惑                          
pmtname,c.ruleid,basictype,subtype,giftremark                        
,p.productname ,1 isSystemAdd,c.pmtid,0,--非积分兑换，使用积分为0 
c.supplierid,c.goodsid,c.rulename,p.imgfolder,p.productimg                             
from  #gift c(nolock) ,#SinpleGift s(nolock),product p(nolock)                        
where 
c.ruleid=s.ruleid and c.productid=p.productid                     

--积分兑换的礼品
insert into giftscart(                            
cartid,productid,productno,marketprice,memberprice,weight                           
,pmtprice,giftnumber,subweight,submoney,lessmoney,giftremark                         
,productname,isSystemAdd,UseScore,supplierid,goodsid,ImgFolder,ProductImg                         
)
select @cartid,s.productid,p.productno,p.marketprice,p.memberprice,p.weight                           
,0 pmtprice,s.quantity,s.quantity*p.weight,0 submoney,p.memberprice*s.quantity lessmoney,'积分兑换' giftremark                        
,p.productname ,0 isSystemAdd,s.giftscore,p.supplierid,s.goodsid,p.imgfolder,p.productimg                               
from  shoppingcart s(nolock),product p(nolock)                       
where 
s.cartid=@cartid and s.ptype=2 and s.productid=p.productid

--6.2.4 删除系统自动添加的礼品信息                       
delete c                        
from  #gift c(nolock) ,#SinpleGift s(nolock)                        
where c.ruleid=s.ruleid   

--6.2.5 可选礼品信息表                       
delete from GiftsCart_temp where cartid=@cartid                        
insert into GiftsCart_temp(                            
cartid,productid,productno,marketprice,memberprice                            
,pmtprice,giftnumber,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,giftremark,productname                  
)                         
select @cartid,p.productid,p.productno,c.marketprice,c.memberprice                            
,pmtprice,c.giftnumber,c.memberprice*giftnumber submoney,c.pmtprice*giftnumber lessmoney,                            
c.pmtname,c.ruleid,basictype,subtype,giftremark,p.productname              
from  #gift c(nolock),product p(nolock)                        
where c.productid=p.productid

                           
                     
--7 购物车信息          
--7.1显示购物车商品信息      
print('output->7.1显示购物车商品信息')                          
select '' as 购物车商品信息,
c.* from                             
--#cart c(nolock)
goodscart c(nolock)
where cartid=@cartid and quantity>0 and supplierID=@sid
order by sort

--统计银行促销商品数量,实际应用时根据bankno来识别不同银行的活动商品
--bankno 1:中国银行;2:工商银行;3:建设银行;4:农业银行;5:招商银行;6:交通银行;7:光大银行
select @banknum=count(1) from #cart c(nolock) where isnull(c.bankno,'-1')<>'-1'
                           
--7.2显示购物车礼品信息
print('output->7.2显示购物车礼品信息')                                                      
select '' as 购物车礼品信息,
c.*,c.giftnumber*usescore as UsedTotalScore                   
from giftscart c(nolock)                
where cartid=@cartid and supplierid=@sid             
                       
/*
--7.3需要用户自己选择的礼品，需要会员自己决定手工将礼品加入到礼品表中 
if coalesce(@memberid, -1)=-1                         
begin  
--未登录会员不显示礼品信息 
print('output->7.3未登录会员不显示可选择礼品信息')                                             
select top 0 c.* ,r.rulename from giftscart_temp c,pmtrule r(nolock) where cartid=@cartid and c.ruleid = r.ruleid                                             
end
                            
else                             
begin 
--已登录会员显示礼品信息 
print('output->7.3已登录会员显示可选择礼品信息')                   
select '' as 可选礼品信息,
c.* ,r.rulename from giftscart_temp c,pmtrule r(nolock) where cartid=@cartid and c.ruleid = r.ruleid                                      
end
*/

--7.4订单信息 
--订单商品品种数、商品总数量、总金额、总积分、总优惠的金额 
print('output->7.4订单商品品种数、商品总数量、总金额、总获得积分、总使用积分、总的积分抵扣金额、总优惠的金额')
select cartid,count(productid) as goodsnumber,sum(quantity) as totalnumber ,sum(subweight) as totalweight,sum(submoney-scoremoney) as totalmoney ,sum(score) as totalscore,sum(usescore) as usedscore,sum(scoremoney) as totalscoremoney,sum(LessMoney) as totallessmoney                        
into #ordermessage                  
from                        
(                        
select cartid,productid,goodsid,quantity,subweight,submoney,Score,UseScore,ScoreMoney,LessMoney,supplierid                         
from goodscart g(nolock)                        
where cartid=@cartid and supplierid=@sid                       
union                        
select cartid,productid,goodsid,giftnumber,subweight,submoney, 0 Score,UseScore,0 ScoreMoney,LessMoney,supplierid                         
from giftscart g(nolock)                        
where cartid=@cartid and supplierid=@sid                       
) as t                        
group by cartid
select @pdtPrice=totalmoney,@weight=totalweight from #ordermessage
select * from #ordermessage

--7.5显示套装信息
print('output->7.5显示套装信息')   
select '' as 套装信息,
*,(MarketPrice-MemberPrice) as LessMoney 
from suitscart 
where cartid=@cartid and supplierid=@sid

--7.6显示单品返券
print('output->7.6显示单品返券')   
select '单品返券' as 单品返券,c.couponname,c.number as number,g.productid,g.goodsid,t.supplierid
from #cart t,pmtrule r(nolock),pmtgoods g(nolock),pmtcoupons c(nolock)
where t.productid=g.productid and g.ruleid=r.ruleid and r.basictype='goods' and r.subtype='coupon' and getdate() between BeginTime and EndTime and c.ruleid=r.ruleid and r.supplierid=t.supplierid


--7.7订单金额优惠信息,暂时不做                                        
print('output->7.7订单金额优惠信息,暂时不做')                            
select top 1 '订单优惠金额暂时先不做' as 订单优惠金额暂时先不做,
* from #orderpromotion



/*
print('debug->商品购物车') 
select '商品购物车' as debug商品购物车,
* from goodscart
print('debug->礼品购物车')                           
select '礼品购物车' as debug礼品购物车,
* from giftscart                    
*/
                     
--declare @shipfeer money,@CouponValue money,
--declare @ordermoney money                      
--select @shipfeer=0                  
--select @CouponValue=0                      
--select @ordermoney=(select top 1 totalmoney from #ordermessage)                      
                      
/*
print('--10.5运费  ')                                            
delete from ShipCart where cartid=@cartid                      
insert into ShipCart(cartid,shipfeer,memberid)                       
values(@cartid,@shipfeer,@memberid)                      
                    
select shipfeer=@shipfeer                      
print('--10.6优惠券')                      
select   CouponValue ,CouponName                      
into #CouponCart                      
from CouponCart c(nolock),CouponDetail d(nolock)                      
where c.CartID=@CartID                      
and d.CouponID=c.CouponID                   
and c.CouponID in (select CouponID from goodscart(nolock) where cartid=@cartid)                    
select * from #CouponCart                      
select @CouponValue=(select  isnull(sum(CouponValue),0)  from #CouponCart)                      
*/
              
--print('output->应付款')                      
--select neepaymoney=@ordermoney+@shipfeer-@CouponValue                      
--select neepaymoney=@ordermoney 

/*                   
print('10.8参与活动或者是其它信息')                     
if object_id('tempdb.dbo.#activelist_temp') is not null                    
begin                    
drop table #activelist_temp                    
end                    
create table #activelist_temp                    
(                    
activename varchar(1000) default '',                    
tipmessage varchar(200) default ''                    
)                    
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;">满50元可使用5元优惠券（促销商品除外）</span>',tipmessage='满50元可使用5元优惠券'                     
                    
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;">满100元可使用10元优惠券（促销商品除外）</span>',tipmessage='满100元可使用10元优惠券'                     
                
                
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;"><a href="products/product-1100530.html">5L金龙鱼花生浓香调和油特价每人限购1瓶</a></span>',tipmessage='5L金龙鱼花生浓香调和油特价每人限购1瓶,数量有限'      
where getdate() between getdate()-5 and  '2010-12-01'                 
                
select  *  from #activelist_temp  
*/

END



















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CatBrand_Get]    脚本日期: 04/09/2012 18:26:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-12-15>
-- Description:	<获取所有品牌页面的分类及品牌数据>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_CatBrand_Get] 
AS
BEGIN
--获取一级分类
select Categoryid,[name],CategoryNo from category where isactive=1 and IsDeleted=0 and categoryid>2 and depth=0 order by sort
--获取分类品牌关联表
select b.brandid,b.brandname,b.logo,b.actid,left(t.categoryno,4) as cno
into #c
from catbrand c(nolock),brand b(nolock),Category t(nolock) 
where c.brandid=b.brandid and c.categoryid=t.categoryid 
order by c.sort

select * from #c group by brandid,brandname,logo,actid,cno
END







GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Category_Add]    脚本日期: 04/09/2012 18:26:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-12-26>
-- Description:	<后台增加商品分类>
-- =============================================
CREATE PROC [dbo].[XpProc_Category_Add]
	@Name nvarchar(100),
	@TypeID int=0,
	@ParentNo numeric(30, 0)=null,
	@parentID int=null,
	@CanAdd tinyint=1,
	@ProductNum int=0,
	@ProductPageSize int=10,
	@InBar tinyint=1,
	@InNav tinyint=1,
	@isactive tinyint=1,
	@isdeleted tinyint=0,
	@isshow tinyint=1,
	@PicsAndCSS ntext = NULL,
	@Logo nvarchar(510) = NULL,
	@ProductAd ntext = NULL,
	@HeadAd ntext = NULL,
	@LastUpdate smalldatetime = NULL,
	@Child int = NULL,
	@brandIDs varchar(8000)=null,
	@NewsCatID int = 0,
	@ScoreRate float = NULL,
	@BPRate float = NULL,
	@sort int=null,

	--记录日志用到以下变量
	@adminID int,
	@adminName nvarchar(50),
	@RealName varchar(20),
	@IP nvarchar(20),
	@errorFlag int output,--错误标志
	@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorFlag=0,@errorMsg='成功添加分类'
Begin Try
--select *from category
--父分类集，用','分割,分类编号
declare @step int,@depth int,@categoryno numeric(30,0)
select @parentno=categoryno FROM Category where categoryid=@parentid

select @step=3--分类步长为3 categoryNO格式为 1 1001 1001001 1001001001
--获取层级
select @depth=len(@parentno)/@step

--如果@categoryno存在子分类，就取最大值+1
--如果@categoryno不存在说明，这个父分类下还没有子分类，要按格式生成新的子分类
select @categoryno=max(categoryno)+1 from category(nolock) where parentno=@parentno
if @categoryno is null
select @CategoryNo=@parentno*1000+1

--有排序sort就按sort排序，没有的话就取max(sort)+1
if isnull(@sort,-1)=-1
select @sort=ISNULL(Max(Sort),0) + 1 From Category(nolock)

begin tran
INSERT INTO Category (CategoryNo,[Name],TypeID,ParentNo,CanAdd,ProductNum,ProductPageSize,InBar,InNav,PicsAndCSS,Logo,
ProductAd,HeadAd,LastUpdate,Depth,Child,Sort,IsActive,IsDeleted,IsShow,Hit,NewsCatID,ScoreRate)
VALUES (@categoryNo ,@name,@typeID,@ParentNo,@canAdd,@productNum ,@productPageSize,@inBar,@inNav,@picsAndCSS,@logo,
@productAd,@headAd,getDate(),@depth,0,@sort,1,0,1,0,@newsCatID,@scoreRate)

declare @categoryid int
select @categoryid =@@identity

--有品牌的话，要把分类关联的品牌ID写到Catbrand表中
if isnull(@brandIDs,'')<>''
INSERT INTO CatBrand (CategoryID,BrandID,Sort,AddTime)
select @@identity,value,1,getDate() from SplitToTable_Func(@brandIDs,',')

--更新父类的子分类数目,及子分类childids
update category set child=isnull(child,0)+1 where categoryno=@parentno

--添加日志
declare @description varchar(510)
select @description='添加商品分类:'+@name
exec XpProc_EventLog_Insert @adminID,@adminName,@RealName,4,41,@description,@IP
select @errorFlag=0
select @errorMsg ='成功添加商品分类' 
commit tran
End Try
Begin Catch
-- 捕捉错误
rollback tran
select @errorFlag=1
select @errorMsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
End
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Category_Delete]    脚本日期: 04/09/2012 18:26:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-12-26>
-- Description:	<描述>
-- =============================================
CREATE PROC [dbo].[XpProc_Category_Delete]
	@CategoryID int,
	@adminID int=null,
	@adminName nvarchar(50)=null,
	@RealName varchar(20)=null,
	@IP nvarchar(20)=null,
	@errorFlag int=null output,--错误标志
	@errorMsg varchar(200)=null output--错误信息
AS
BEGIN
select @errorFlag=1,@errorMsg=''

Begin Try

declare @child int,@name varchar(100)
select @child=child,@name=name from category c(nolock) where categoryid=@categoryid
if @child>0
begin
select @errorflag=-3
select @errormsg='该分类下还有子分类不能删除'
return
end
if exists (Select Top 1 ProductID FROM Product WHERE CategoryID = @categoryID)
begin
select @errorflag=-2
select @errormsg='该分类下还有商品不能删除'
return
end

begin tran
--父类的子类数量-1，商品数量不用更新，因为要删除的分类必须是没有商品的
update b set b.child=b.child-1
from category a(nolock),category b(nolock)
where a.categoryid=@categoryid and a.parentno=b.categoryno
DELETE Category WHERE CategoryID = @CategoryID

--删除catbrand表中的数据
delete from catbrand where categoryid=@categoryid
--添加日志
declare @description varchar(510)
select @description='删除商品分类:'+@name
exec XpProc_EventLog_Insert @adminID,@adminName,@RealName,4,43,@description,@IP
select @errorFlag=0
select @errorMsg='分类已删除'
commit tran
End Try
Begin Catch
rollback tran
-- 捕捉错误
select @errorflag=1
select @errorMsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
End




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Category_Get]    脚本日期: 04/09/2012 18:26:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-12-17>
-- Description:	<按要求获得所有的分类>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Category_Get] 
@catID int=null,
@showall bit=null,
@inbar bit=null,
@innav bit=null,
@isactive bit=null,
@isshow bit=null,
@isonlyfirst bit=null,
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
declare @sqlstr nvarchar(4000),@where nvarchar(4000)

select @errorflag=0,@errormsg=''
Begin Try
select CategoryID,Name,Depth,CategoryNo,ParentNo,ProductNum,InNav,InBar,Sort,IsActive,IsDeleted,IsShow,Child,ChildIDs,CanAdd ,Logo 
from Category 
where categoryid>0 
ORDER BY Sort

End Try
Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Category_Update]    脚本日期: 04/09/2012 18:26:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-12-26>
-- Description:	<后台修改商品分类>
-- =============================================
CREATE PROC [dbo].[XpProc_Category_Update]
	@CategoryID int,
	@Name nvarchar(100)=null,
	@TypeID int=0,
	@ParentNo numeric(30, 0)=null,
	@parentID int=null,
	@CanAdd tinyint=1,
--	@ProductNum int=0,
@url varchar(50)=null,
@color varchar(50)=null,
	@ProductPageSize int=10,
@listStyle int=null,
@categoryStyle int=null, 
@categoryTemplateID int=null, 
@productTemplateID int=null, 
@newWindow tinyint=null,
	@InBar tinyint=1,
	@InNav tinyint=1,
@IsActive tinyint=1,
@IsDeleted tinyint=1,
@isshow tinyint=1,
	@PicsAndCSS ntext = NULL,
	@Logo nvarchar(510) = NULL,
	@ProductAd ntext = NULL,
	@HeadAd ntext = NULL,
	@LastUpdate smalldatetime = NULL,
	@Child int = NULL,
	@brandIDs varchar(8000)=null,
	@NewsCatID int = 0,
	@ScoreRate float = NULL,
	@BPRate float = NULL,
	@sort int=null,

	--记录日志用到以下变量
	@adminID int=null,
	@adminName nvarchar(50)=null,
	@RealName varchar(20)=null,
	@IP nvarchar(20)=null,
	@errorFlag int=null output,--错误标志
	@errorMsg varchar(200)=null output--错误信息
AS
BEGIN
select @errorFlag=0,@errorMsg=''
Begin Try
--判断不能选择类别自身以及其子类别作为父级类别
if exists(select a.categoryid from category a ,Category b
where b.categoryid=@categoryid
and left(a.categoryno,len(b.categoryno))=b.categoryno and a.categoryid=@parentid)
begin
select @errorFlag=1
select @errorMsg='不能选择类别自身以及其子类别作为父级类别'
return
end
begin tran
UPDATE	Category
SET
--	CategoryNo = @CategoryNo,
	Name = @Name,
	TypeID = @TypeID,
--	ParentNo = @ParentNo,
--	CanAdd = @CanAdd,
--	ProductNum = @ProductNum,
	ProductPageSize = @ProductPageSize,
	InBar = @InBar,
	InNav = @InNav,
--	PicsAndCSS = @PicsAndCSS,
	Logo = @Logo,
	ProductAd = @ProductAd,
	HeadAd = @HeadAd,
	LastUpdate = getDate(),

--	Depth = @Depth,
--	Child = @Child,
--	Sort = @Sort,
--	IsActive = @IsActive,
--	IsDeleted = @IsDeleted,
--	IsShow = @IsShow,
--	Hit = @Hit,
	NewsCatID = COALESCE(@NewsCatID, (0)),
	ScoreRate = @ScoreRate
--	BPRate = @BPRate
WHERE 	CategoryID = @CategoryID

--有品牌的话，先删除以前的关联的id,然后要把分类关联的品牌ID写到Catbrand表中
delete from CatBrand where categoryid=@categoryid
if isnull(@brandIDs,'')<>''
begin
INSERT INTO CatBrand (CategoryID,BrandID,Sort,AddTime)
select @categoryid,value,1,getDate() from SplitToTable_Func(@brandIDs,',')
end

--当前类categoryno
declare @categoryno numeric(30,0)
select @categoryno=categoryno from category c(nolock) where categoryid=@categoryid
--当前分类下的所有的商品数量（包含子分类的商品数量）
declare @totalproduct int
select @totalproduct=count(productid) from product p(nolock)where p.categoryno like ''+ cast(@categoryno as nvarchar(30))+'%' 
--更新当前分类的商品数量
update category set productnum=@totalproduct where categoryid=@categoryid

--判断是否分类是否有变化，没有变化就不用更新改分类相关的一些字段比如categoryno ,parentno
--if not exists(select categoryno from category b(nolock) 
--where exists (select categoryno from category c(nolock) where c.categoryno=b.parentno and categoryid=@parentid)
--and b.categoryid=@categoryid)
if not exists(select *from category c,category b where c.categoryno=b.parentno and b.categoryid=@categoryid and c.categoryid=@parentid)
begin
--修改父分类时，父类要更新child
--子分类也要更改相关的parentno,categoryno
--parentid新的父分类id categoryid 当前的分类id

--获得父分类的子分类的最大值,父类的depth,父类的parentpath,父类的categoryno作为子类的parentno
declare @tempcategoryno decimal(30,0),@depth int,@parentpath varchar(8000)
select @tempcategoryno=categoryno,@depth=depth,@parentpath=parentpath,@parentno=categoryno
from category c(nolock) 
where c.categoryid=@parentid
select @tempcategoryno=isnull(max(categoryno),@tempcategoryno*1000)+1
from category c(nolock) 
where c.parentno=@tempcategoryno

--更新原来的父类的子类个数
update c set c.child=c.child-1 
from category c ,Category b
where c.categoryno=b.parentno and b.categoryid=@categoryid

--更新新的父类的子类个数
update Category set child=child+1 where categoryid=@parentid

--更新原父类(包含父类的父类）的商品数量
update a set a.productnum=a.productnum-@totalproduct
from category a ,Category b
where b.categoryid=@categoryid
and left(b.categoryno,len(a.categoryno))=a.categoryno and a.categoryid<@categoryid

--更新新的父类(包含父类的父类）的商品数量
update a set a.productnum=a.productnum+@totalproduct
from category a ,category b
where b.categoryid=@parentid 
and left(b.categoryno,len(a.categoryno))=a.categoryno

--递归查出所有的子类（包含当前分类）
;
----更新所有的子类的categoryno,parentno,parentpath,childids
--with temp as 
--( 
--select categoryid,categoryno ,parentno  from category c where c.categoryid=@categoryid
--union all 
--select c.categoryid,c.categoryno ,c.parentno from temp t 
--inner join category c 
--on t.categoryno=c.parentno 
--) 
--更新category中跟分类相关的字段
update category set categoryno=
cast(@tempcategoryno as nvarchar(30))+
substring(cast(categoryno as nvarchar(30)),len(cast(@categoryno as nvarchar(30)))+1,len(categoryno)),
parentno=substring(cast(@tempcategoryno as nvarchar(30))+
substring(cast(categoryno as nvarchar(30)),len(cast(@categoryno as nvarchar(30)))+1,len(categoryno)),0,len(cast(@tempcategoryno as nvarchar(30))+
substring(cast(categoryno as nvarchar(30)),len(cast(@categoryno as nvarchar(30)))+1,len(categoryno)))-2),
depth=(len(cast(@tempcategoryno as nvarchar(30))+
substring(cast(categoryno as nvarchar(30)),len(cast(@categoryno as nvarchar(30)))+1,len(categoryno)))-3)/3
where categoryno like ''+ cast(@categoryno as nvarchar(30))+'%'

--更新商品表中的categoryno
update product set categoryno=cast(@tempcategoryno as nvarchar(30))+
substring(cast(categoryno as nvarchar(30)),len(cast(@categoryno as nvarchar(30)))+1,len(categoryno))
where categoryno like ''+ cast(@categoryno as nvarchar(30))+'%'
--select categoryno, *from product
--where categoryno like ''+ cast(@categoryno as nvarchar(30))+'%'

--更新pdttag表中的Categoryno
update pdttag set categoryno=cast(@tempcategoryno as nvarchar(30))+
substring(cast(categoryno as nvarchar(30)),len(cast(@categoryno as nvarchar(30)))+1,len(categoryno))
where categoryno like ''+ cast(@categoryno as nvarchar(30))+'%'


--添加日志
declare @description varchar(510)
select @description='修改商品分类:'+@name
exec XpProc_EventLog_Insert @adminID,@adminName,@RealName,4,42,@description,@IP

select @errorflag=0
select @errorMsg='更新成功，分类已更新'
end
else
begin
select @errorflag=0
select @errorMsg='更新成功'
end
commit tran
End Try

Begin Catch
rollback tran
-- 捕捉错误
select @errorflag=1
select @errorMsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
End




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CatPdtNum_Update]    脚本日期: 04/09/2012 18:26:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2009-08-19>
-- Description:	< 重新统计所有分类的商品数量>
-- =============================================
create PROCEDURE [dbo].[XpProc_CatPdtNum_Update] 
AS
begin
--统计最低级商品数量
select p.categoryid,c.categoryno,count(productid) as num
into #cpn
from product p(nolock),category c(nolock)
where 
p.categoryid = c.categoryid and p.status>0 and isforsale=1 and isdel=0
group by  p.categoryid,c.categoryno

--统计所有分类的商品数量
select c.categoryid,c.categoryno,sum(isnull(t.num,0)) productnum
into #Category
from category c
left join #cpn t
on
c.categoryno=left(t.categoryno,len(c.categoryno))
group by c.categoryid,c.categoryno

--更新所有分类的商品数量
update  c set ProductNum=t.productnum                
from  Category c(nolock),#Category t(nolock)                
where                 
c.CategoryID=t.CategoryID
 end


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CatRelateInfo_Select]    脚本日期: 04/09/2012 18:26:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[XpProc_CatRelateInfo_Select]
@cid varchar(20)
as
begin
--获取分类关联的品牌
select b.brandid,b.brandname from category c(nolock),catbrand cb(nolock),brand b(nolock) where c.categoryno=@cid and c.categoryid=cb.categoryid and cb.brandid=b.brandid

--获取分类关联的属性、参数、主规格、次规格
select t.props,t.paras,t.prop1,t.prop2 from category c(nolock),pdttype t(nolock) where c.typeid=t.typeid and c.categoryno=@cid

--获取分类关联的主规格、次规格
select p.pid,p.pname,v.vid,v.vname from category c(nolock),pdttype t(nolock),prop p(nolock),propvalue v(nolock) where c.typeid=t.typeid and c.categoryno=@cid and t.prop1=p.pid and p.pid=v.pid order by v.sort

--获取分类关联的次规格
select p.pid,p.pname,v.vid,v.vname from category c(nolock),pdttype t(nolock),prop p(nolock),propvalue v(nolock) where c.typeid=t.typeid and c.categoryno=@cid and t.prop2=p.pid and p.pid=v.pid order by v.sort

end




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Channel_Init]    脚本日期: 04/09/2012 18:26:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-03-27>
-- Description:	<初始化频道页的数据>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Channel_Init] 
@cid int,--频道对应分类ID
@errorFlag int=null output,--错误标志
@errorMsg varchar(200)=null output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''
Begin Try
--获取频道信息
select [Name],ProductAD,HeadAD from category where CategoryID=@cid and depth=0

--厨窗基本设置
select FloorID,FloorName,TopAD,ContentAD,Backgroundimage,Sort,Status
into #f
from [floor](nolock) 
where supplierid=0 and CatID=@cid and status=1 
order by sort asc
select * from #f

--厨窗推荐产品
select fp.FloorID,fp.ProductID,fp.GoodsID,fp.Sort,ImgFolder,ProductImg,thumbnailimg,img5,productname,shortdesc,marketprice,isnull(l.pmtprice,p.memberprice) as memberprice,case when l.subtype='limittime' then 16 when l.subtype='specialprice' then 2 when l.subtype='coupon' then 10 when PiEndTime>getdate() then PiNo else 0 end as PiNo 
from product p(nolock),#f f,floorpdt fp(nolock)
left join PmtGoodsList l(nolock) on fp.productid=l.productid
where f.floorid=fp.floorid and fp.productid=p.productid

--获取频道对应的活动专场
SELECT top 6 activityid,title 
FROM Activity 
WHERE CategoryID=@cid and Status=1
ORDER BY ActivityID DESC

--获取频道对应的推荐品牌
SELECT top 14 b.BrandID,BrandName,b.Logo,ActID 
FROM Brand b(nolock),CatBrand cb(nolock),category c(nolock),category c1(nolock) 
WHERE b.BrandID=cb.BrandID and cb.categoryid=c.categoryid and c.categoryno Like convert(varchar(20),c1.categoryno)+'%' and c1.categoryid=@cid
group by b.BrandID,b.BrandName,b.Logo,b.Sort,ActID 
order by b.Sort

--获取频道对应的推荐商品
select top 5
p.ProductID,ProductName,marketprice,memberprice,ThumbnailImg,ProductImg,ImgFolder,Img5 
FROM Product p(nolock),PdtTag t(nolock),category c(nolock)
Where t.tagid=3 and t.ishomeshow=0 and c.categoryid=@cid and c.categoryno=left(t.categoryno,len(c.categoryno)) and t.ProductID = p.ProductID and p.Status > 0 and p.IsForSale=1
order by t.sort desc

--获取频道对应的新品推介
select top 4
p.ProductID,ProductName,marketprice,memberprice,ThumbnailImg,ProductImg,ImgFolder,Img5 
FROM Product p(nolock),PdtTag t(nolock),category c(nolock)
Where t.tagid=6 and t.ishomeshow=0 and c.categoryid=@cid and c.categoryno=left(t.categoryno,len(c.categoryno)) and t.ProductID = p.ProductID and p.Status > 0 and p.IsForSale=1
order by t.sort desc

End Try
Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Checkout_Init]    脚本日期: 04/09/2012 18:26:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		<Hakkas>
-- Create date: <2011-04-05>
-- Description:	<初始化订单确认页面>
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110725                              
content:                                
1.添加参数@banknum记录购物车是否包含银行促销商品,如果包含，只能选择该银行对应的支付接口支付                              
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Checkout_Init]
@cartid varchar(36),--购物车ID
@memberid int, --会员ID
@sid int, --商家ID
@errorFlag int out,--错误标志：0无错误，1有错误
@errorMsg varchar(200) out--错误信息,当@errorFlag=1是要显示错误信息
AS
BEGIN
--exec XpProc_Checkout_Init 'bed4026f-684b-4056-8843-0111c090b7bd',2,0

/*=========================清空购物车优惠券信息开始==============================*/  
print('订单确认页面刷新页面，要清空下已使用优惠券的信息')
--取消购物车中的优惠券信息
update c set CouponID=null,couponvalue=null
from goodscart c(nolock)
where c.CartID=@CartID and c.supplierid=@sid
--删除购物车优惠券
delete from CouponCart where CartID=@CartID and memberid=@memberid and supplierid=@sid
/*=========================清空购物车优惠券信息结束==============================*/  

--获取商家购物车信息
print('output->1:获取商家购物车信息')
declare @pdtPrice money,--商品金额
@weight decimal(18,2),--商品重量
@banknum int --银行活动商品数量
exec XpProc_CartStore_Look @cartid,@memberid,@sid,@pdtPrice out,@weight out,@banknum out
--1284546465 许生
--获取会员地址簿
print('output->2:获取会员地址簿')
SELECT * into #r FROM ReceiverAddress(nolock) WHERE MemberID=@memberid ORDER BY ReceiverAddressID
select * from #r

--获取商家的支付方式
print('output->3:获取商家的支付方式')
if @banknum>0
select * from PayType(nolock) where paytypeid=1
else
select * from PayType(nolock) where (sid=@sid or sid=-1) and Status = 1 order by Sort asc


--获取配送方式
print('output->4:获取配送方式')
--获取会员的第一个地址簿的二级地区ID
declare @areaid int,@areaidforprice int,@addressid varchar(100)
select @areaid=-1,@addressid=''
select top 1 @addressid=addressid from #r
if @addressid<>''
begin
select @areaid=value from SplitToTable_Func(@addressid,',') where id=2
select @areaidforprice=value from SplitToTable_Func(@addressid,',') where id=1
end
exec XpProc_AreaShipping_Get @areaid,@areaidforprice,@pdtPrice,@weight,0,@sid

--获取电子优惠券
print('output->5:获取电子优惠券')
SELECT cm.UID,cm.CouponCode,cm.OrderID,c.CouponName,c.BeginTime,c.EndTime,c.Type,c.Status As CouponsStatus,cm.Status As CouponsMemberStatus,case when isnull(cm.remark,'')='' then '' else '('+cm.remark+')' end as remark
FROM CouponsMember cm(nolock)
left join Coupon c(nolock) 
ON cm.CouponID = c.CouponID
Where MemberID= @memberID And GetDate() Between cm.BeginTime And cm.EndTime And cm.Status = 1 and cm.IsUsed=0 and cm.MinMoney<=@pdtPrice

END




















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CheckoutFQ_Init]    脚本日期: 04/09/2012 18:26:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		<Hakkas>
-- Create date: <2011-04-05>
-- Description:	<初始化分期订单确认页面>
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110725                              
content:                                
                             
*/
-- =============================================
Create PROCEDURE [dbo].[XpProc_CheckoutFQ_Init]
@cartid varchar(36),--购物车ID
@memberid int, --会员ID
@sid int, --商家ID
@errorFlag int out,--错误标志：0无错误，1有错误
@errorMsg varchar(200) out--错误信息,当@errorFlag=1是要显示错误信息
AS
BEGIN
--exec XpProc_Checkout_Init 'bed4026f-684b-4056-8843-0111c090b7bd',2,0
/*=========================清空购物车优惠券信息开始==============================*/  
print('订单确认页面刷新页面，要清空下已使用优惠券的信息')
--取消购物车中的优惠券信息
update c set CouponID=null,couponvalue=null
from goodscart c(nolock)
where c.CartID=@CartID and c.supplierid=@sid
--删除购物车优惠券
delete from CouponCart where CartID=@CartID and memberid=@memberid and supplierid=@sid
/*=========================清空购物车优惠券信息结束==============================*/  

--获取商家购物车信息
print('output->1:获取商家购物车信息')
declare @pdtPrice money,--商品金额
@weight decimal(18,2),--商品重量
@banknum int --银行活动商品数量
exec XpProc_CartStore_Look @cartid,@memberid,@sid,@pdtPrice out,@weight out,@banknum out

--获取会员地址簿
print('output->2:获取会员地址簿')
SELECT * into #r FROM ReceiverAddress(nolock) WHERE MemberID=@memberid ORDER BY ReceiverAddressID
select * from #r

--获取支持分期付款银行
select bankid,bankname 
from bank 
where supportfq=1

--获取分期付款银行支持的分期数
--declare @pdtprice decimal(18,2)
--select @pdtprice=1000
select q.bankid,q.periods,q.rate,@pdtPrice*q.rate as totalmoney,(@pdtPrice+@pdtPrice*q.rate)/periods as fqmoney,convert(decimal(18,2),round((@pdtPrice+@pdtPrice*q.rate)/periods,2)) as fqmoney1
from bank b,bankfq q
where b.supportfq=1 and b.bankid=q.bankid
order by periods asc


--获取配送方式
print('output->4:获取配送方式')
--获取会员的第一个地址簿的二级地区ID
declare @areaid int,@areaidforprice int,@addressid varchar(100)
select @areaid=-1,@addressid=''
select top 1 @addressid=addressid from #r
if @addressid<>''
begin
select @areaid=value from SplitToTable_Func(@addressid,',') where id=2
select @areaidforprice=value from SplitToTable_Func(@addressid,',') where id=1
end
exec XpProc_AreaShipping_Get @areaid,@areaidforprice,@pdtPrice,@weight,0,@sid

--获取电子优惠券
print('output->5:获取电子优惠券')
SELECT cm.UID,cm.CouponCode,cm.OrderID,c.CouponName,c.BeginTime,c.EndTime,c.Type,c.Status As CouponsStatus,cm.Status As CouponsMemberStatus,case when isnull(cm.remark,'')='' then '' else '('+cm.remark+')' end as remark
FROM CouponsMember cm(nolock)
left join Coupon c(nolock) 
ON cm.CouponID = c.CouponID
Where MemberID= @memberID And GetDate() Between cm.BeginTime And cm.EndTime And cm.Status = 1 and cm.IsUsed=0 and cm.MinMoney<=@pdtPrice

END




















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CheckoutSecKill_Init]    脚本日期: 04/09/2012 18:26:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Hakkas>
-- Create date: <2011-04-05>
-- Description:	<初始化秒杀订单确认页面>
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110725                              
content:                                                              
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_CheckoutSecKill_Init]
@cartid varchar(36),--购物车ID
@memberid int, --会员ID
@sid int=0, --商家ID
@errorFlag int out,--错误标志：0无错误，1有错误
@errorMsg varchar(200) out--错误信息,当@errorFlag=1是要显示错误信息
AS
BEGIN
--insert log(content)values(@cartid)
--exec XpProc_Checkout_Init 'bed4026f-684b-4056-8843-0111c090b7bd',2,0
if not exists(select uid from memberbookseckill(nolock) where uid=@cartid and status=0)
begin
select @errorFlag=1
select @errorMsg='这个秒杀已生成订单，请不要重复提交！'
return
end
/*=========================清空购物车优惠券信息开始==============================*/  
print('订单确认页面刷新页面，要清空下已使用优惠券的信息')
--取消购物车中的优惠券信息
update c set CouponID=null,couponvalue=null
from goodscart c(nolock)
where c.CartID=@CartID and c.supplierid=@sid
--删除购物车优惠券
delete from CouponCart where CartID=@CartID and supplierid=@sid
/*=========================清空购物车优惠券信息结束==============================*/  

--获取商家购物车信息
print('output->0:获取购物车信息')
select @cartid as cartid,s.ruleid,s.rulename,s.productid,s.goodsid,s.productname,s.pmtprice,s.quantity,s.supplierid,p.productno,p.marketprice,
p.memberprice,p.weight,p.score,p.ImgFolder,p.ProductImg,p.MiniBuyNum,p.IsOfferInvoice
into #cart 
from MemberBookSecKill s(nolock),Product p(nolock) 
where s.uid=@cartid and s.productid=p.productid

declare @pdtprice decimal(18,2),--商品金额
@weight decimal(18,2)--商品重量
select @sid=supplierid,@pdtprice=pmtprice*quantity,@weight=weight*quantity from #cart
                          
delete from goodscart where cartid=@cartid                                                     
insert into goodscart(                     
cartid,productid,productname,productno,marketprice,memberprice,weight,                          
pmtprice,quantity,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,remark,                        
GoodsID, IsDlvUnit, DlvUnit,MiniBuyNum,Score,                        
StowageID,IsOfferInvoice,RecordID,ProductSpecs                      
,pmtid,IsDiscount,UseScore,ScoreMoney,SupplierID,RuleName,ImgFolder,ProductImg,suitid                         
)                            
select @cartid,productid,productname,productno,marketprice,memberprice,weight,                        
pmtprice,quantity,weight*quantity as subweight,pmtprice*quantity as submoney,(memberprice-pmtprice)* quantity as lessmoney,                            
rulename,ruleid,'goods' as basictype,'seckill' as subtype,'秒杀' as remark,                        
GoodsID, 0 IsDlvUnit,0 DlvUnit,MiniBuyNum,Score*quantity as subscore,                        
0 StowageID,IsOfferInvoice,0 RecordID,'' ProductSpecs                        
,0 pmtid,0 IsDiscount,0 UseScore,0 scoremoney,SupplierID,RuleName,ImgFolder,ProductImg,0 as suitid                           
from  #cart c(nolock)

--获取购物车汇总信息
print('output->0:获取购物车商品信息')                       
select '' as 购物车商品信息,
c.* from
goodscart c(nolock)
where cartid=@cartid 
--and quantity>0
order by sort

--获取购物车汇总信息
print('output->1:获取购物车汇总信息')
select quantity as totalnumber,pmtprice*quantity as TotalMoney,weight*quantity as totalweight,score*quantity as totalscore,(memberprice-pmtprice)*quantity as totallessmoney 
from #cart

--获取会员地址簿
print('output->2:获取会员地址簿')
SELECT * into #r FROM ReceiverAddress(nolock) WHERE MemberID=@memberid ORDER BY ReceiverAddressID
select * from #r

--获取商家的支付方式
print('output->3:获取商家的支付方式')
select * from PayType(nolock) where paytypeid=1
--select * from PayType(nolock) where (sid=@sid or sid=-1) and Status = 1 order by Sort asc


--获取配送方式
print('output->4:获取配送方式')
--获取会员的第一个地址簿的二级地区ID
declare @areaid int,@areaidforprice int,@addressid varchar(100)
select @areaid=-1,@addressid=''
select top 1 @addressid=addressid from #r
if @addressid<>''
begin
select @areaid=value from SplitToTable_Func(@addressid,',') where id=2
select @areaidforprice=value from SplitToTable_Func(@addressid,',') where id=1
end
exec XpProc_AreaShipping_Get @areaid,@areaidforprice,@pdtPrice,@weight,0,@sid

--获取电子优惠券
print('output->5:获取电子优惠券')
SELECT cm.UID,cm.CouponCode,cm.OrderID,c.CouponName,c.BeginTime,c.EndTime,c.Type,c.Status As CouponsStatus,cm.Status As CouponsMemberStatus,case when isnull(cm.remark,'')='' then '' else '('+cm.remark+')' end as remark
FROM CouponsMember cm(nolock)
left join Coupon c(nolock) 
ON cm.CouponID = c.CouponID
Where MemberID= @memberID And GetDate() Between c.BeginTime And c.EndTime And c.Status = 1 and cm.IsUsed=0

END




















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CheckoutSucc_Init]    脚本日期: 04/09/2012 18:26:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-07-25>
-- Description:	<订单生成页面初始化订单及支付信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_CheckoutSucc_Init]
	@orderid int
AS
BEGIN
--获取订单金额信息
select orderno,PayType,PayTypeName,totalprice,(AdvancePayment+ScoreAmount) as payedmoney,needPaymoney 
from orders o(nolock)
left join paytype p(nolock) on o.paytype=p.paytypeid
where orderid=@orderid

--获取支付在线支付方式
--如果存在银行促销商品，则只能选择该银行对应的支付接口进行支付，实际操作过程中可以修改bankno和InterfaceID来更改银行支付接口
--bankno 1:中国银行;2:工商银行;3:建设银行;4:农业银行;5:招商银行;6:交通银行;7:光大银行;8:中国银联
select r.bankno into #b from orderproduct p(nolock),pmtrule r(nolock) 
where p.orderid=@orderid and p.ruleid=r.ruleid and isnull(r.bankno,'-1')<>'-1'
group by r.bankno

declare @banknum int
select @banknum=count(1)from #b

if @banknum>0
begin
select PaymentID,[Name],Description
from Payment p(nolock),#b b
--where InterfaceID=32 --31:招商银行信用卡支付;32:交通银行;33:上海银联;34:招商银行综合支付接口;35:工商银行;37:光大银行;38:农业银行
where p.paymentid=b.bankno
and status=1
end
else
begin
select PaymentID,[Name],Description
from Payment p(nolock),orders o(nolock) 
where p.PayType=o.PayType and p.Status=1 and o.orderid=@orderid 
Order By Sort
end

SELECT z.ZtdNo,z.ZtdName,z.Address,z.Remark 
FROM Ztd z(nolock),orders o(nolock) 
WHERE z.ZtdNo = o.ZtdNo and o.orderid=@orderid

END









GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Common_Random_Cet]    脚本日期: 04/09/2012 18:26:34 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-09-01>
-- Description:	<生成10位以内的随机数>
/*debug
declare @random varchar(10)
exec XpProc_Common_Random_Cet 5,@random out
select @random
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Common_Random_Cet]
	@lenght int,--随机数的长度
	@random varchar(10) output--返回生成的随机数
AS
BEGIN
declare @n int,@m int,@index int
select @n=0,@m=10,@index=0,@random=''
while @index<@lenght
begin
select @random=@random+cast(cast((rand()*(@m-@n)+@n) as int) as varchar(10))
select @index=@index+1
end
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Coupon_Add]    脚本日期: 04/09/2012 18:26:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-06-27>
-- Description:	<添加优惠券>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Coupon_Add]
	@CouponName nvarchar(50) = NULL,
	@CouponValue money = NULL,
	--@RuleID int = NULL,
	--@Prefix nvarchar(100) = NULL,
	--@GenQuantity int = NULL,
	--@CouponKey nvarchar(100) = NULL,
	@BeginTime datetime = NULL,
	@EndTime datetime = NULL,
	@Status int = NULL,
	@Type int = NULL,
	--@Score int = NULL,
	--@Disabled int = NULL,
	@SupplierID int = NULL,
	@TotalNumber int = NULL,
	--@UsedNumber int = NULL,
	@MinMoney money = NULL,
	@SuitType varchar(20) = NULL,
	@SuitValue varchar(20) = NULL,
	@Remark varchar(100) = NULL,
	@AddUser int = NULL,
	@AddUserName varchar(20) = NULL,
	@AddIP varchar(50) = NULL,
	@AddTime datetime = NULL
AS

INSERT coupon(
CouponName, CouponValue, BeginTime, EndTime, Status, Type,SupplierID, TotalNumber,MinMoney, SuitType, SuitValue, Remark, AddUser, AddUserName, AddIP, AddTime
--RuleID, Prefix, GenQuantity, CouponKey,  Score, Disabled,UsedNumber
)
VALUES (
@CouponName, @CouponValue, @BeginTime, @EndTime, COALESCE(@Status, (1)), COALESCE(@Type, (1)),COALESCE(@SupplierID, (0)), @TotalNumber,COALESCE(@MinMoney, (0)), COALESCE(@SuitType, '所有'), COALESCE(@SuitValue, 'all'), @Remark, @AddUser, @AddUserName, @AddIP, COALESCE(@AddTime, getdate())
--@RuleID, @Prefix, COALESCE(@GenQuantity, (0)), @CouponKey,  @Score, COALESCE(@Disabled, (0)), COALESCE(@UsedNumber, (0))
)

RETURN SCOPE_IDENTITY()


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Coupon_Cancle]    脚本日期: 04/09/2012 18:26:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-03-01>
-- Description:	<取消使用优惠券>
-- =============================================
CREATE proc [dbo].[XpProc_Coupon_Cancle]
@CartID varchar(50),--购物车ID
@UID int, --优惠券ID
@MemberID varchar(50), --会员ID
@SupplierID int, --商家ID
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
as
BEGIN
Begin Try
begin tran
--1.1取消购物车中的优惠券信息
update c set CouponID=null,couponvalue=null
from goodscart c(nolock)
where c.CouponID=@UID and c.CartID=@CartID and c.supplierid=@SupplierID
--1.2删除购物车优惠券
delete from CouponCart where CouponID=@UID and CartID=@CartID and supplierid=@SupplierID
--返回结果
select @errorFlag=0,@errorMsg=''
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Coupon_Exchange]    脚本日期: 04/09/2012 18:26:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-03-01>
-- Description:	<兑换优惠券>
-- =============================================
CREATE proc [dbo].[XpProc_Coupon_Exchange]
@couponid int,--优惠券ID
@memberid int, --会员ID
@num int=null, --兑换数量
@ip varchar(50),--兑换者IP
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
as
BEGIN
select @errorFlag=0,@errorMsg=''
Begin Try
begin tran
declare @membername varchar(20),@mobile varchar(20),@score int,@needscore int
--1.1获取会员当前积分
select @membername=[name],@mobile=mobile,@score=score from member where memberid=@memberid
select @needscore=score*@num from Coupon where couponid=@couponid
--1.2足够积分的话派发优惠券
if @score>=@needscore
begin
--派发优惠券
exec XpProc_Coupon_Issue @couponid,@memberid,@membername,@num,0,'积分兑换优惠券',0,'积分兑换优惠券',@membername,@IP
--扣减会员积分
update member set score=score-@needscore
--写积分日志
exec XpProc_ScoreLog_Insert @memberid,@mobile,@needscore,-1,1,0,null,'兑换优惠券','','兑换优惠券扣减积分','兑换优惠券扣减积分',@ip,null,null,@memberid,@membername
end
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Coupon_Issue]    脚本日期: 04/09/2012 18:26:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-07-19>
-- Description:	<发放优惠券>
/*
debug:exec  XpProc_Coupon_Issue @couponid=1,@memberid=2,@number=10,@supplierid=0,@SendReason='新店开张每人送10张10元优惠券',@ispublic=0
*/
/*引用该存储过程的存储过程有
1、XpProc_Member_Insert
2、XpProc_OrderStatus_BatchUpdate
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Coupon_Issue]
@couponid int,--优惠券ID
@memberid int=null,--会员ID
@membername varchar(50)=null,--会员账号
@number int=1,--发放数量
@supplierid	int=0,	--商家ID
@SendReason varchar(100)=NULL,
@ispublic bit=0,--是否公有
@Remark varchar(100)=NULL,
@AddUserName varchar(20)='system',
@IP varchar(50)=NULL,
@GetMethod tinyint=1,--派发途径：1线下派发，2为积分兑换，3为订单赠送，4为注册赠送，5管理员手工发放，
@BeginTime datetime=null,--有效开始日期
@EndTime datetime=null,--有效截止日期
@errorFlag int output,--错误标识
@errorMsg varchar(200) output--错误信息
AS
BEGIN
if isnull(@memberid,-1)=-1 and isnull(@membername,'')=''
	begin
	select @errorflag=1,@errormsg='会员资料不存在'
	return
	end 
else if isnull(@memberid,-1)=-1 and isnull(@membername,'')<>''
	begin
	select @memberid=memberid from member m(nolock) where [name]=@membername and status=1
	end
else if isnull(@memberid,-1)<>-1 and isnull(@membername,'')=''
	begin
	select @membername=[name] from member m(nolock) where memberid=@memberid and status=1
	end

if not exists(select memberid from member where memberid=isnull(@memberid,-1) and [name]=isnull(@membername,'') and status=1)
begin
select @errorflag=1,@errormsg='会员资料不存在'
return
end

declare 
@CouponName nvarchar(200),--优惠券名称
@CouponValue money,--优惠券面值
@MinMoney money,--使用优惠券的最低订单金额
@SuitType varchar(20),--限制使用类型
@SuitValue varchar(20),--限制使用类型对应的值
@Prefix varchar(50),--优惠券号前导符
@CouponKey varchar(50),--优惠券密钥
@type int,--类型
@TotalNumber int,--总数
@GenQuantity int,--已派发数量
@num int

select @CouponName=CouponName,@CouponValue=CouponValue,@Prefix=Prefix,@CouponKey=CouponKey,@type=type,@Begintime=isnull(@Begintime,BeginTime),
@EndTime=isnull(@EndTime,EndTime),@SupplierID=SupplierID,@MinMoney=MinMoney,@SuitType=SuitType,@SuitValue=SuitValue,@remark=isnull(@remark,Remark),
@TotalNumber=totalnumber,@GenQuantity=GenQuantity
from coupon c(nolock)
where c.couponid=@couponid

--当限制派发数量且剩余派发数量小于要派发的数量时要重置派发数量未剩余派发数量
if @TotalNumber>0 and (@TotalNumber-@GenQuantity)< @number
begin
declare @oldnumber int
select @oldnumber=@number
select @number=@TotalNumber-@GenQuantity
end
--select * from coupon where couponid=1

--派发优惠券
select @num=0
while @num<@number
begin
INSERT couponsmember(CouponID, CouponName, CouponValue, MemberID,MemberName,SuitType, SuitValue, MinMoney,SendReason,Remark, AddUserName, AddUserIP,IsPublic,BeginTime,EndTime,Prefix,CouponKey,Type,GetMethod,SupplierID)
VALUES (@CouponID, @CouponName, @CouponValue, @memberid,@membername,@SuitType, @SuitValue, @MinMoney, @SendReason,@Remark, @AddUserName, @IP,@IsPublic,@BeginTime,@EndTime,@Prefix,@CouponKey,@Type,@GetMethod,@SupplierID)
select @num=@num+1
end

--更新优惠券的派发数量
update coupon set GenQuantity=GenQuantity+@num where couponid=@couponid
if @oldnumber>@number
select @errorflag=0,@errormsg='优惠券数量不足，已派发 '+cast(@num as varchar(10))+' 张'
else
select @errorflag=0,@errormsg='优惠券已派发'

END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Coupon_Update]    脚本日期: 04/09/2012 18:26:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-06-27>
-- Description:	<更改优惠券>
-- =============================================
create PROCEDURE [dbo].[XpProc_Coupon_Update]
	@CouponID int,
	@CouponName nvarchar(50) = NULL,
	@CouponValue money = NULL,
	--@RuleID int = NULL,
	--@Prefix nvarchar(100) = NULL,
	--@GenQuantity int = NULL,
	--@CouponKey nvarchar(100) = NULL,
	@BeginTime datetime = NULL,
	@EndTime datetime = NULL,
	@Status int = NULL,
	@Type int = NULL,
	--@Score int = NULL,
	--@Disabled int = NULL,
	@SupplierID int = NULL,
	@TotalNumber int = NULL,
	--@UsedNumber int = NULL,
	@MinMoney money = NULL,
	@SuitType varchar(20) = NULL,
	@SuitValue varchar(20) = NULL,
	@Remark varchar(100) = NULL,
	@UpdateUser int = NULL,
	@UpdateUserName varchar(20) = NULL,
	@UpdateTime datetime = NULL
AS
UPDATE	coupon
SET	CouponName = @CouponName,
	CouponValue = @CouponValue,
	--RuleID = @RuleID,
	--Prefix = @Prefix,
	--GenQuantity = COALESCE(@GenQuantity, (0)),
	--CouponKey = @CouponKey,
	BeginTime = @BeginTime,
	EndTime = @EndTime,
	Status = COALESCE(@Status, (1)),
	Type = COALESCE(@Type, (1)),
	--Score = @Score,
	--Disabled = @Disabled,
	SupplierID = COALESCE(@SupplierID, (0)),
	TotalNumber = @TotalNumber,
	--UsedNumber = COALESCE(@UsedNumber, (0)),
	MinMoney = COALESCE(@MinMoney, (0)),
	SuitType = COALESCE(@SuitType, '所有'),
	SuitValue = COALESCE(@SuitValue, 'all'),
	Remark = @Remark,
	UpdateUser = @UpdateUser,
	UpdateUserName = @UpdateUserName,
	UpdateTime = @UpdateTime
WHERE 	CouponID = @CouponID


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Coupon_Use]    脚本日期: 04/09/2012 18:26:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-03-01>
-- Description:	
--使用优惠券
--1.按优惠券号码查询优惠券是否存在
--2.计算此优惠券的适用范围的订单金额
--3.比较优惠券的起始金额与订单总金额
--4.删除订单中已经存在的此优惠券的信息，防止多次提交功能

/*
debug:exec  XpProc_Coupon_Issue @couponid=1,@memberid=2,@number=10,@supplierid=0,@SendReason='新店开张每人送10张10元优惠券'
*/
-- =============================================
CREATE proc [dbo].[XpProc_Coupon_Use]
@UID int=null,--优惠券ID
@CouponCode varchar(50)='',--优惠券号
@CartID varchar(50),--购物车ID
@MemberID int, --会员ID
@SupplierID int,--商家ID
@IsValidate int output, --是否通过验证
@ErrorMsg varchar(200) output --错误信息
as
--先取消购物车中的优惠券信息
update c set CouponID=null,CouponValue=null
from goodscart c(nolock)
where c.cartid=@CartID and c.supplierid=@SupplierID
--删除购物车优惠券
delete from CouponCart where cartid=@CartID and supplierid=@SupplierID

--1.0 获取优惠券信息
declare @ordermoney money,--订单可使用优惠券金额
@minmoney money,--优惠券使用起始金额
@pnum int,--适用优惠券的商品数量
@remark varchar(100)--优惠券备注

select @IsValidate=1,@ErrorMsg=''
declare @flag int
select top 1 m.couponid,m.UID,m.couponcode,m.couponname,m.couponvalue,m.begintime,m.endtime,m.type,m.suittype,m.suitvalue,m.minmoney,m.remark
into #CouponDetail
from CouponsMember m(nolock)
where (m.UID=@UID or m.CouponCode=@CouponCode)--根据优惠券ID或编号查找优惠券
and m.status=1
and m.memberid=case when m.ispublic=1 then m.memberid else @MemberID end
and m.IsUsed=0
and getdate() between m.begintime and m.endtime

select @flag=@@ROWCOUNT

--print('debug:1')
--select * from #CouponDetail

if(1=@flag)--查找到相关的优惠券信息
begin
--验证金额是否满足条件
--获取优惠券的适用范围

select @UID=UID,@remark=remark,@minmoney=minmoney from #CouponDetail --输入优惠券号的时候要获取会员优惠券ID

--3.获取购物车商品信息
select c.pmtid,c.cartid,c.quantity,c.submoney,c.ruleid
,p.productid,brandid,p.categoryid,p.categoryno,0 stowageid
into #product
from goodscart c(nolock),product p(nolock)
where 
c.cartid=@cartid
and c.supplierid=@SupplierID --该商家的商品
and p.productid=c.productid
and coalesce(c.CouponID, 0)=0--未使用优惠券的商品

--print('debug:2')
--select * from goodscart

--4.删除不参与优惠券活动的商品
delete p
from #product p(nolock),pmtlist l(nolock)
where 
p.pmtid=l.pmtid
and isnull(l.IsCanUsedCoupon,0)<>1 

--5计算可以使用优惠券的订单商品金额
select distinct p.*,c.CouponID,c.MinMoney,c.UID,c.CouponValue
into #cp 
from #product p(nolock),#CouponDetail c(nolock)
where 
p.cartid=@cartid
and (c.SuitValue=
case 
when  suitType='商品' then convert(varchar(20),p.productid)
when  suitType='类别' then left(convert(varchar(20),p.categoryno),len(SuitValue))
when  suitType='品牌' then convert(varchar(20),p.brandid)
when  suitType='仓位' then convert(varchar(20),p.stowageid)
when  suitType='所有' then 'all'
else '-null--1'
end
)

select @pnum=isnull(sum(p.quantity),0),@ordermoney=isnull(sum(p.submoney),0)
from #cp p(nolock) --按活动来计算金额
--select @pnum,@ordermoney

print('先判断有无适用该优惠券的商品再判断订单金额是否满足使用条件')
if @pnum>0
begin

if(@MinMoney<=@ordermoney)
begin
 select @IsValidate=1
 --更新购物车中可以使用优惠券的商品
 update c set CouponID=p.UID,CouponValue=p.CouponValue
 from GoodsCart c(nolock),#cp p(nolock)
 where c.cartid=@cartid
 and c.supplierid=@supplierid
 and p.productid=c.productid
 --删除重复的优惠券信息
 delete 
 from CouponCart 
 where CouponID=@UID and CartID=@CartID and supplierid=@supplierid--防止多次使用
 -- 添加使用的优惠券信息
 insert into CouponCart(CouponID,CartID,Memberid,SupplierID)
 values(@UID,@CartID,@Memberid,@SupplierID)
end
else--订单金额小于最小可使用金额
begin
 select @IsValidate=0
 select @ErrorMsg='在订单中至少需要：'+convert(varchar(20),@MinMoney)+'元,才能使用此优惠券,当前购物车符合条件的商品金额为:' +convert(varchar(20),@ordermoney)
end
end
else
begin
select @IsValidate=0
select @ErrorMsg=case when isnull(@remark,'')='' then '没有符合适用该优惠券的商品' else '没有符合适用该优惠券的商品,优惠券适用条件：'+@remark end
end

end 
else
begin
select @IsValidate=0
 select @ErrorMsg='不存在此优惠券或者已经失效!'
end

--------------- 返回结果信息  ----------------------------------------- 
--返回优惠券明细
select UID, CouponName,CouponValue
from #CouponDetail d(nolock)



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Coupon_Use_20110816]    脚本日期: 04/09/2012 18:26:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-03-01>
-- Description:	
--使用优惠券
--1.按优惠券号码查询优惠券是否存在
--2.计算此优惠券的适用范围的订单金额
--3.比较优惠券的起始金额与订单总金额
--4.删除订单中已经存在的此优惠券的信息，防止多次提交功能

/*
debug:exec  XpProc_Coupon_Issue @couponid=1,@memberid=2,@number=10,@supplierid=0,@SendReason='新店开张每人送10张10元优惠券'
*/
-- =============================================
create proc [dbo].[XpProc_Coupon_Use_20110816]
@UID int=null,--优惠券ID
@CouponCode varchar(50)='',--优惠券号
@CartID varchar(50),--购物车ID
@MemberID int, --会员ID
@SupplierID int,--商家ID
@IsValidate int output, --是否通过验证
@ErrorMsg varchar(200) output --错误信息
as
--先取消购物车中的优惠券信息
update c set CouponID=null,CouponValue=null
from goodscart c(nolock)
where c.cartid=@CartID and c.supplierid=@SupplierID
--删除购物车优惠券
delete from CouponCart where cartid=@CartID and supplierid=@SupplierID

--1.0 获取优惠券信息
declare @ordermoney money,--订单可使用优惠券金额
@minmoney money--优惠券使用起始金额

select @IsValidate=1,@ErrorMsg=''
declare @flag int
select top 1 c.couponid,m.UID,m.couponcode,c.couponname,c.couponvalue,c.begintime,c.endtime,c.type,m.suittype,m.suitvalue,m.minmoney
into #CouponDetail 
from CouponsMember m(nolock),Coupon c(nolock)
where (m.UID=@UID or m.CouponCode=@CouponCode)--根据优惠券ID或编号查找优惠券
and m.status=1
and m.memberid=@MemberID
and m.couponid=c.couponid 
and c.status=1 and getdate() between c.begintime and c.endtime

select @flag=@@ROWCOUNT

--print('debug:1')
--select * from #CouponDetail

if(1=@flag)--查找到相关的优惠券信息
begin
--验证金额是否满足条件
--获取优惠券的适用范围

select @UID=UID,@minmoney=minmoney from #CouponDetail --输入优惠券号的时候要获取会员优惠券ID

--3.获取购物车商品信息
select c.pmtid,c.cartid,c.submoney,c.ruleid
,p.productid,brandid,p.categoryid,p.categoryno,0 stowageid
into #product
from goodscart c(nolock),product p(nolock)
where 
c.cartid=@cartid
and c.supplierid=@SupplierID --该商家的商品
and p.productid=c.productid
and coalesce(c.CouponID, 0)=0--未使用优惠券的商品

--print('debug:2')
--select * from goodscart

--4.删除不参与优惠券活动的商品
delete p
from #product p(nolock),pmtlist l(nolock)
where 
p.pmtid=l.pmtid
and isnull(l.IsCanUsedCoupon,0)<>1 

--5计算可以使用优惠券的订单商品金额
select distinct p.*,c.CouponID,c.MinMoney,c.UID,c.CouponValue
into #cp 
from #product p(nolock),#CouponDetail c(nolock)
where 
p.cartid=@cartid
and (c.SuitValue=
case 
when  suitType='商品' then convert(varchar(20),p.productid)
when  suitType='类别' then left(convert(varchar(20),p.categoryno),len(SuitValue))
when  suitType='品牌' then convert(varchar(20),p.brandid)
when  suitType='仓位' then convert(varchar(20),p.stowageid)
when  suitType='所有' then 'all'
else '-null--1'
end
) 

select  @ordermoney=isnull(sum(p.submoney),0)
from #cp p(nolock) --按活动来计算金额

if(@MinMoney<=@ordermoney)
begin
 select @IsValidate=1
 --更新购物车中可以使用优惠券的商品
 update c set CouponID=p.UID,CouponValue=p.CouponValue
 from GoodsCart c(nolock),#cp p(nolock)
 where c.cartid=@cartid
 and c.supplierid=@supplierid
 and p.productid=c.productid
 --删除重复的优惠券信息
 delete 
 from CouponCart 
 where CouponID=@UID and CartID=@CartID and supplierid=@supplierid--防止多次使用
 -- 添加使用的优惠券信息
 insert into CouponCart(CouponID,CartID,Memberid,SupplierID)
 values(@UID,@CartID,@Memberid,@SupplierID)
end
else--订单金额小于最小可使用金额
begin
 select @IsValidate=0
 select @ErrorMsg='在订单中至少需要：'+convert(varchar(20),@MinMoney)+'元,才能使用此优惠券,当前购物车符合条件的商品金额为:' +convert(varchar(20),@ordermoney)
end

end 
else
begin
select @IsValidate=0
 select @ErrorMsg='不存在此优惠券或者已经失效!'
end

--------------- 返回结果信息  ----------------------------------------- 
--返回优惠券明细
select UID, CouponName,CouponValue
from #CouponDetail d(nolock)





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Coupon_Use_20111013]    脚本日期: 04/09/2012 18:26:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-03-01>
-- Description:	
--使用优惠券
--1.按优惠券号码查询优惠券是否存在
--2.计算此优惠券的适用范围的订单金额
--3.比较优惠券的起始金额与订单总金额
--4.删除订单中已经存在的此优惠券的信息，防止多次提交功能

/*
debug:exec  XpProc_Coupon_Issue @couponid=1,@memberid=2,@number=10,@supplierid=0,@SendReason='新店开张每人送10张10元优惠券'
*/
-- =============================================
CREATE proc [dbo].[XpProc_Coupon_Use_20111013]
@UID int=null,--优惠券ID
@CouponCode varchar(50)='',--优惠券号
@CartID varchar(50),--购物车ID
@MemberID int, --会员ID
@SupplierID int,--商家ID
@IsValidate int output, --是否通过验证
@ErrorMsg varchar(200) output --错误信息
as
--先取消购物车中的优惠券信息
update c set CouponID=null,CouponValue=null
from goodscart c(nolock)
where c.cartid=@CartID and c.supplierid=@SupplierID
--删除购物车优惠券
delete from CouponCart where cartid=@CartID and supplierid=@SupplierID

--1.0 获取优惠券信息
declare @ordermoney money,--订单可使用优惠券金额
@minmoney money,--优惠券使用起始金额
@pnum int,--适用优惠券的商品数量
@remark varchar(100)--优惠券备注

select @IsValidate=1,@ErrorMsg=''
declare @flag int
select top 1 c.couponid,m.UID,m.couponcode,c.couponname,c.couponvalue,c.begintime,c.endtime,c.type,m.suittype,m.suitvalue,m.minmoney,m.remark
into #CouponDetail 
from CouponsMember m(nolock),Coupon c(nolock)
where (m.UID=@UID or m.CouponCode=@CouponCode)--根据优惠券ID或编号查找优惠券
and m.status=1
and m.memberid=case when m.ispublic=1 then m.memberid else @MemberID end
and m.couponid=c.couponid 
and m.IsUsed=0
and c.status=1 and getdate() between c.begintime and c.endtime

select @flag=@@ROWCOUNT

--print('debug:1')
--select * from #CouponDetail

if(1=@flag)--查找到相关的优惠券信息
begin
--验证金额是否满足条件
--获取优惠券的适用范围

select @UID=UID,@remark=remark,@minmoney=minmoney from #CouponDetail --输入优惠券号的时候要获取会员优惠券ID

--3.获取购物车商品信息
select c.pmtid,c.cartid,c.quantity,c.submoney,c.ruleid
,p.productid,brandid,p.categoryid,p.categoryno,0 stowageid
into #product
from goodscart c(nolock),product p(nolock)
where 
c.cartid=@cartid
and c.supplierid=@SupplierID --该商家的商品
and p.productid=c.productid
and coalesce(c.CouponID, 0)=0--未使用优惠券的商品

--print('debug:2')
--select * from goodscart

--4.删除不参与优惠券活动的商品
delete p
from #product p(nolock),pmtlist l(nolock)
where 
p.pmtid=l.pmtid
and isnull(l.IsCanUsedCoupon,0)<>1 

--5计算可以使用优惠券的订单商品金额
select distinct p.*,c.CouponID,c.MinMoney,c.UID,c.CouponValue
into #cp 
from #product p(nolock),#CouponDetail c(nolock)
where 
p.cartid=@cartid
and (c.SuitValue=
case 
when  suitType='商品' then convert(varchar(20),p.productid)
when  suitType='类别' then left(convert(varchar(20),p.categoryno),len(SuitValue))
when  suitType='品牌' then convert(varchar(20),p.brandid)
when  suitType='仓位' then convert(varchar(20),p.stowageid)
when  suitType='所有' then 'all'
else '-null--1'
end
)

select @pnum=isnull(sum(p.quantity),0),@ordermoney=isnull(sum(p.submoney),0)
from #cp p(nolock) --按活动来计算金额
--select @pnum,@ordermoney

print('先判断有无适用该优惠券的商品再判断订单金额是否满足使用条件')
if @pnum>0
begin

if(@MinMoney<=@ordermoney)
begin
 select @IsValidate=1
 --更新购物车中可以使用优惠券的商品
 update c set CouponID=p.UID,CouponValue=p.CouponValue
 from GoodsCart c(nolock),#cp p(nolock)
 where c.cartid=@cartid
 and c.supplierid=@supplierid
 and p.productid=c.productid
 --删除重复的优惠券信息
 delete 
 from CouponCart 
 where CouponID=@UID and CartID=@CartID and supplierid=@supplierid--防止多次使用
 -- 添加使用的优惠券信息
 insert into CouponCart(CouponID,CartID,Memberid,SupplierID)
 values(@UID,@CartID,@Memberid,@SupplierID)
end
else--订单金额小于最小可使用金额
begin
 select @IsValidate=0
 select @ErrorMsg='在订单中至少需要：'+convert(varchar(20),@MinMoney)+'元,才能使用此优惠券,当前购物车符合条件的商品金额为:' +convert(varchar(20),@ordermoney)
end
end
else
begin
select @IsValidate=0
select @ErrorMsg='没有符合适用该优惠券的商品'+',优惠券适用条件：'+@remark
end

end 
else
begin
select @IsValidate=0
 select @ErrorMsg='不存在此优惠券或者已经失效!'
end

--------------- 返回结果信息  ----------------------------------------- 
--返回优惠券明细
select UID, CouponName,CouponValue
from #CouponDetail d(nolock)


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CouponPmt_Get]    脚本日期: 04/09/2012 18:26:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-09-29>
-- Description:	<获取优惠券派发途径>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_CouponPmt_Get] 
@couponid int
AS
BEGIN
select r.ruleid,isnull(r.remark,r.rulename) as rulename,r.basictype,r.subtype
from PmtCoupons c(nolock),PmtRule r(nolock)
where c.ruleid=r.ruleid and c.couponid=@couponid
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CouponsMember_Get]    脚本日期: 04/09/2012 18:26:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-05-21>
-- Description:	<会员中心分页获取我的优惠券>
-- Debug:

-- =============================================
CREATE PROCEDURE [dbo].[XpProc_CouponsMember_Get]
@flag varchar(20),--active:未使用；used:已使用；out:已过期
@memberid int,--会员id
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@totalpage int output,--总页数
@totalcount int output,--总记录数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000),@sort varchar(50)
select @sort=' order by uid desc'
select @where = ' ispublic=0'

select @flag=isnull(@flag,'active')
if @flag='active'
select @where=@where+'  and IsUsed=0 and endtime > getdate()'
else if @flag='used'
select @where=@where+' and isused=1',@sort=' order by usedtime desc'
else if @flag='out'
select @where=@where+' and isused=0 and endtime<getdate()'

select @where=@where+' and memberid='+convert(varchar(20),@memberid)

select @sqlstr='select rowno,uid,SendReason,minmoney,CouponName,CouponCode,CouponValue,AddTime,begintime,endtime,UsedTime,Status,IsUsed,orderno,remark from (
select uid,SendReason,minmoney,couponname,couponcode,couponvalue,addtime,begintime,endtime,UsedTime,Status,IsUsed,orderno,remark,Row_number() over('

if isnull(@sort,'')<>''
select @sqlstr=@sqlstr+@sort
else
select @sqlstr=@sqlstr+'order by uid desc'

select @sqlstr=@sqlstr+ ') as rowno 
from CouponsMember(nolock)'

select @sqlstr=@sqlstr+' where ' + @where + ') as l where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

--print @sqlstr
--insert into log(content) values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数

select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by uid desc) as rowno from CouponsMember(nolock)'
select @sqlstr=@sqlstr++' where ' + @where + ') as l )'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END









GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CouponsMember_PageList_Get]    脚本日期: 04/09/2012 18:26:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-05-21>
-- Description:	<分页获取优惠券使用记录>
-- Debug:

-- =============================================
CREATE PROCEDURE [dbo].[XpProc_CouponsMember_PageList_Get]
@keyword varchar(50)=null,--优惠券号
@searchtype varchar(10)=1,--1:优惠券号;2:优惠券名称
@type int=-1,--类型
@minusetimes varchar(10),--最小使用次数
@maxusetimes varchar(10),--最大使用次数
@membername varchar(20)=null,--使用者账号
@stime varchar(20)='',--开始时间
@etime varchar(20)='',--结束时间
@susetime varchar(20)='',--使用次数下限
@eusetime varchar(20)='',--使用次数上限
@isused varchar(10),--是否已使用
@supplierid int=0,--商家ID
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@totalpage int output,--总页数
@totalcount int output,--总记录数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000),@sort varchar(50)
select @sort=' order by CM.AddTime desc'
select @where = ' 1=1'

if isnull(@keyword,'')<>''
begin
if isnull(@searchtype,'1')='1'
select @where=@where+' and cm.couponcode='''+@keyword+''''
else
select @where=@where+' and cm.couponname='''+@keyword+''''
end

if isnull(@type,'-1')<>'-1'
begin
select @where=@where+' and cm.type='+convert(varchar(20),@type)
if @type='0'
begin
if isnull(@minusetimes,'')<>''
select @where=@where+' and cm.UsedTimes >='+@minusetimes
if isnull(@maxusetimes,'')<>''
select @where=@where+' and cm.UsedTimes <='+@maxusetimes
end
end

if isnull(@membername,'')<>''
select @where=@where+' and cm.membername=''' + @membername+''''

if isnull(@stime,'')<>''
select @where=@where+' and cm.begintime >= '''+@stime+ ''''

if isnull(@etime,'')<>''
select @where=@where+' and cm.endtime <= '''+@etime+ ''''

if isnull(@susetime,'')<>''
select @where=@where+' and cm.UseTime >= '''+@susetime+ ''''

if isnull(@eusetime,'')<>''
select @where=@where+' and cm.UseTime <= '''+@eusetime+ ''''

if isnull(@isused,'-1')='1'
select @where=@where+'  and CM.usedTimes > 0'

if isnull(@isused,'-1')='0'
select @where=@where+'  and CM.usedTimes = 0'


select @sqlstr='select rowno,CouponID,CouponName,CouponCode,CouponValue,AddTime,MemberID,membername as MemberName,UsedTime,UsedTimes,Status,IsUsed from (
select cm.couponid,cm.couponname,cm.couponcode,cm.couponvalue,cm.addtime,cm.MemberID,cm.membername,cm.UsedTime,cm.UsedTimes,cm.Status,cm.IsUsed ,Row_number() over('

if isnull(@sort,'')<>''
select @sqlstr=@sqlstr+@sort
else
select @sqlstr=@sqlstr+'order by cm.addtime desc'

select @sqlstr=@sqlstr+ ') as rowno 
from CouponsMember cm(nolock)'

select @sqlstr=@sqlstr+' where ' + @where + ') as l where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

--print @sqlstr
--insert into log(content) values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数

select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by cm.uid desc) as rowno from CouponsMember cm(nolock)'

select @sqlstr=@sqlstr++' where ' + @where + ') as l )'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END










GO
/****** 对象:  StoredProcedure [dbo].[XpProc_CouponWaitIssue_Get]    脚本日期: 04/09/2012 18:26:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-10-8>
-- Description:	<获取未过去的优惠券>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_CouponWaitIssue_Get]
AS
BEGIN
select CouponID,CouponName,CouponValue,1 as PmtNumber,0 as IsSelected,30 as Validity
from coupon 
where getdate()<EndTime and status=1
END





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Default_Init]    脚本日期: 04/09/2012 18:26:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-03-27>
-- Description:	<初始化前台首页的数据>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Default_Init] 
@errorFlag int=null output,--错误标志
@errorMsg varchar(200)=null output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''
Begin Try
--厨窗基本设置
select FloorID,FloorName,TopAD,ContentAD,Backgroundimage,Sort,Status
into #f
from [floor](nolock) 
where supplierid=0 and CatID=0 and status=1 
order by sort asc
select * from #f
--厨窗推荐产品
select fp.FloorID,fp.ProductID,fp.GoodsID,fp.Sort,ImgFolder,ProductImg,thumbnailimg,productname,shortdesc,marketprice,isnull(l.pmtprice,p.memberprice) as memberprice,case when l.subtype='limittime' then 16 when l.subtype='specialprice' then 2 when l.subtype='coupon' then 10 when PiEndTime>getdate() then PiNo else 0 end as PiNo 
from product p(nolock),#f f,floorpdt fp(nolock)
left join PmtGoodsList l(nolock) on fp.productid=l.productid
where f.floorid=fp.floorid and fp.productid=p.productid
End Try
Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_EvalReply_Insert]    脚本日期: 04/09/2012 18:26:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-04-27>
-- Description:	<根据ShopEvalID,在EvalReply表中插入一条纪录,商家对顾客的一个评价进行回复>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_EvalReply_Insert] (
@seid int  , --顾客的一个评价的ShopEvalID
@body ntext,--回复的内容
@ip nvarchar(40),--商家的IP
@sid int ,--商家ID
@userName varchar(20),--操作员ID
@errorFlag int=0 output
)
AS
Begin
select @errorFlag=-1
begin transaction
--根据ShopEvalID,增加商家对一个评价的回复
--取得商家名称

insert EvalReply(ShopEvalID,SupplierID,Body,ReplyTime,IP,Status,UserName)VALUES(@seid,@sid,@body,getDate(),@ip,1,@userName)
--设置ShopEval表中的IsReply=1表示商家对这个评价已回复
update ShopEval set IsReply=1 where ShopEvalID=@seid
set @errorFlag=0
commit transaction
End


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_EventLog_Add]    脚本日期: 04/09/2012 18:26:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-09-13>
-- Description:	<添加系统日志>
-- =============================================
create PROC [dbo].[XpProc_EventLog_Add]
@adminid int=null,--操作员ID
@adminname varchar(50)=null,--操作员姓名
@RootCatID int=Null,--一级事件分类ID
@SubCatID int=null, --二级事件分类ID
@OPDesc varchar(500) = NULL,--操作描述
@ip varchar(50) =NULL --操作人ip
AS
begin
INSERT INTO EventLog (MemberID,MemberName,RootCatID,SubCatID,Description,IP) 
VALUES 
(@adminid,@adminname,@RootCatID,@SubCatID,@OPDesc,@ip)
end
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_EventLog_Insert]    脚本日期: 04/09/2012 18:26:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-08-20>
-- Description:	<添加系统事件日志>
/*
引用该存储过程的存储过程：
1、XpProc_PdtStatus_Update
2、XpProc_Admin_Login
3、XpProc_AppForm_Delete
*/
-- =============================================
CREATE PROC [dbo].[XpProc_EventLog_Insert]
@MemberID	int,--管理员ID
@MemberName	nvarchar(50)=null,--管理员账号
@RealName varchar(20)=null,--真实姓名
@RootCatID	int=null,--日志主分类ID
@SubCatID	int=null,--日志子分类ID
@Description	nvarchar(255)=null,--描述
@IP	nvarchar(20)=null--IP
AS

if(@memberid is not null and @membername is null)
select @membername=AdminName from admin(nolock) where adminid=@memberid

INSERT eventlog(
MemberID,MemberName,RealName,RootCatID,SubCatID,Description,IP)
VALUES (
@MemberID,COALESCE(@MemberName,''),COALESCE(@RealName,''),COALESCE(@RootCatID,0),COALESCE(@SubCatID,0),COALESCE(@Description,''),COALESCE(@IP,('0.0.0.0')))





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ExportFinanceSummaries]    脚本日期: 04/09/2012 18:26:47 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--后台商家财务明细统计中导出FinanceSummaries表中的数据到电子表格中
CREATE  procedure [dbo].[XpProc_ExportFinanceSummaries]
(
@keys varchar(1000), --条件where子句
@sort varchar(50)   --排序
)
as
begin
set nocount on

declare @sql varchar(8000)
set @sql='select issue,amount,tuikuan,yongjin,shifu,CASE status  WHEN 2 THEN ''可以结款'' WHEN 3 THEN ''结款中''  when 4 then ''结款完成''else '''' END from (select * from(select financesummariesid, case when grouping(financesummariesid)=1 and grouping(issue)=1 then '+' ''总计'' '+' else issue end  as issue,sum(amount) as amount,sum(tuikuan)as tuikuan,sum(yongjin)as yongjin,sum(amount)-sum(tuikuan)-sum(yongjin) as shifu,status
from financesummaries where '+ @keys+' group by financesummariesid ,issue ,status with rollup)a where issue is not null and status is not null or issue='+' ''总计'' '+')b order by '+@sort+' desc'
exec (@sql) 
end















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ExportFinanceSummary]    脚本日期: 04/09/2012 18:26:48 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--后台商家财务明细统计中导出FinanceSummary表中的数据到电子表格中
CREATE  procedure [dbo].[XpProc_ExportFinanceSummary]
(
@keys varchar(1000), --条件where子句
@sort varchar(50)   --排序
)
as
begin
set nocount on

declare @sql varchar(8000)

set @sql='select b.issue,b.amount,b.tuikuan,b.yongjin,b.shifu,CASE b.status  WHEN 2 THEN ''可以结款'' WHEN 3 THEN ''结款中''  when 4 then ''结款完成''else '''' END,
s.SupplierName,s.bankno,s.bankAddress,s.bankaccount from (select * from(select financesummaryid, case when grouping(financesummaryid)=1 and grouping(issue)=1 and grouping(supplierid)=1 then '+' ''总计'' '+' else issue end issue,sum(amount) as amount,sum(tuikuan)as tuikuan,sum(yongjin)as yongjin,sum(amount)-sum(tuikuan)-sum(yongjin) as shifu,STATUS,case when grouping(supplierid)=1 then null  else supplierid end supplierid 
from financesummary where '+ @keys+' group by financesummaryid ,supplierid,issue ,status with rollup)a where issue is not null and supplierid is not null and status is not null or issue='+' ''总计'' '+')b
left join supplier s on b.supplierid=s.supplierid order by '+@sort+' desc'
exec (@sql)
end



















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FinanceDetail_Insert]    脚本日期: 04/09/2012 18:26:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<当向Orders表插入记录时，也向FinanceDetail插入相关的字段>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_FinanceDetail_Insert]
@ordertime smalldatetime ,
--@issue varchar(30),
@orderid int,
@orderno nvarchar(50),
@amount money,
@tuikuan money,
@yongjin money ,
@supplierid int,
@status tinyint
AS
BEGIN
	SET NOCOUNT ON;
	insert FinanceDetail(ordertime,issue,orderid,orderno,amount,tuikuan,yongjin,supplierid,status) values(@ordertime,getDate(),@orderid,@orderno,@amount,@tuikuan,@yongjin,@supplierid,@status)
END





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FinanceDetail_Select]    脚本日期: 04/09/2012 18:26:49 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-09>
-- Description:	<用于商家后台，帐户明细，订单付款，结款订单的查询>
-- =============================================
CREATE  procedure [dbo].[XpProc_FinanceDetail_Select]
(
@pagerows int,        --每页行数    
@pageindex int,        --索引
@tab nvarchar(250),    --表名
@keyid nvarchar(50),    --主键
@total nvarchar(4000),    --条件
@sort nvarchar(50),    --排序
@kid nvarchar(500),    --列名
@tt  nvarchar(50), --针对获得总条数时需要的特殊条件，一般为*
@rows int output --总行数
)
as
begin
set nocount on
declare 
@befrows int,
@sql nvarchar(4000),
@sql2 nvarchar(4000)
set @befrows=@pagerows*(@pageindex-1)
--分页信息

--FinanceDetail 与Orders连接，得到Orders.Status
set @sql=
--一页的记录数
'select top '+cast(@pagerows as nvarchar(50))+' *
from(select '+@kid+',Orders.status as ordersstatus ,Orders.PayType as PayType ,ROW_NUMBER() Over(order by FinanceDetail.Orderid desc )as rowid from
 '+@tab+' join orders on orders.orderid=financedetail.orderid  where '+@total+' ) financeOrders
where  financeOrders.rowid > ' +cast(@befrows as nvarchar(50)) 
+'union all '+
--一页的汇总数据
'select null,''本页合计'', cast(sum(amount) as decimal(18,2)) as amount'+',cast(sum(TuiKuan) as decimal(18,2))  as TuiKuan'+',cast(sum(Yongjin) as decimal(18,2)) as Yongjin'+',cast(sum(amount)-sum(TuiKuan)-sum(YongJin) as decimal(18,2)) as ShiFu,null as status ,null,null, null ,null from'+
'(select top '+cast(@pagerows as nvarchar(50))+' *
from(select '+@kid+',Orders.status as ordersstatus ,Orders.PayType as PayType ,ROW_NUMBER() Over(order by FinanceDetail.Orderid desc )as rowid from
 '+@tab+' join orders on orders.orderid=financedetail.orderid  where '+@total+' ) financeOrders where  financeOrders.rowid > ' +cast(@befrows as nvarchar(50)) 
+')a '
+'union all '+
--一次查询的汇总数据
'select null,''本次查询合计'', cast(sum(amount) as decimal(18,2)) as amount'+',cast(sum(TuiKuan) as decimal(18,2))  as TuiKuan'+',cast(sum(Yongjin) as decimal(18,2)) as Yongjin'+',cast(sum(amount)-sum(TuiKuan)-sum(YongJin) as decimal(18,2)) as ShiFu,null as status ,null,null, null ,null from'+
'(select *
from(select '+@kid+',Orders.status as ordersstatus ,Orders.PayType as PayType ,ROW_NUMBER() Over(order by FinanceDetail.Orderid desc )as rowid from
 '+@tab+' join orders on orders.orderid=financedetail.orderid  where '+@total+' ) financeOrders)a '

--统计分页的汇总信息
--set @sql2='select cast(sum(amount) as decimal(18,2)) as amount'+',cast(sum(TuiKuan) as decimal(18,2))  as TuiKuan'+',cast(sum(Yongjin) as decimal(18,2)) as Yongjin'+',cast(sum(amount)-sum(TuiKuan)-sum(YongJin) as decimal(18,2)) as ShiFu from'+'(select top '+cast(@pagerows as nvarchar(50))+' '+@kid+' from '+@tab+' where '+@total+' and '+@keyid+' not in (select top '+cast(@befrows as nvarchar(50))+' '+@keyid+' from '+@tab+' where '+@total+' '+@sort+' )   '+@sort+' )a'
EXEC (@sql)
--EXEC (@sql2)
--print @sql
-------总条数------
set @sql=N'select @rows=count('+@tt+') from '+@tab+' join orders on orders.orderid=financedetail.orderid where '+@total

exec sp_executesql @sql,N'@rows int out',@rows out
select  @rows
return @rows
end
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FinanceDetail_Update]    脚本日期: 04/09/2012 18:26:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<用于更新FinanceDetail,FinanceSummary的表，Status的六种状态为:-1无需结款，0不可结款，1未结款，2可结款 3结款中 4结款完成>
-- =============================================

CREATE PROCEDURE  [dbo].[XpProc_FinanceDetail_Update]
@step int=1, --用于标识执行这个存储过程的哪个部分
@err1 int, --错误标识
@err2 int, --错误标识
@issue nvarchar(30)='' 
AS
BEGIN
if(@step=1) --每天的例行执行
begin
	--Order.PayType 小于6说明的款到发货，=6是货到付款,这二种类型的订单从不可结款到未结款的状态的时间是不同的
	--Order.Status =6已发货，=7已签收
	--通过联接Orders,FinanceDetail两个表，根据FinanceDetail的Status为0的纪录的OrderId，查找Orders表。 因此#temp存的是不可结款的记录。
	select a.orderid,a.ordertime, a.paytype,a.status into #temp from orders a join FinanceDetail b on a.orderid=b.orderid and b.status=0
	--如果#temp的某个记录满足指定的条件则可以说明这个记录是可以从不可结款转变为未结款状态的，并通过OrderId 更新此记录在FinanceDetail中的Status=1
	update FinanceDetail set status=1 where orderid in(select orderid from #temp where 
	(ordertime< dateadd(dd,-5, datediff(dd,0,getDate())) and paytype<5 and stauts=6) or (ordertime< dateadd(dd,-7, datediff(dd,0,getDate())) and paytype=6 and stauts=7))
end
else if(@step=2) --结款日执行
begin
	--先往FinanceSummay表中插入每个供应商本期的结账款
	BEGIN TRANSACTION
--	declare @issue varchar(10)
	select @issue=convert(varchar(10),dateadd(dd,-1,getDate()),120) --生成的ISSUE的值，将要插入到FinanceSummary,FinanceDetail表中
	declare @amount money
	declare @tuikuan money
	declare @yongjin money
	declare @supplierid int
	declare @status int 
	set @status=2
	select sum(amount)as amount,sum(tuikuan)as tuikuan,sum(yongjin)as yongjin,supplierid into #temp2 from FinanceDetail(nolock) where status=1 group by supplierid
	declare tempFinanceSummary cursor for
	select * from #temp2
	open tempFinanceSummary
	fetch next from tempFinanceSummary into @amount,@tuikuan,@yongjin,@supplierid 
	while @@FETCH_STATUS=0
	begin
		insert financeSummary(issue,amount,tuikuan,yongjin,supplierid,status)values(@issue,@amount,@tuikuan,@yongjin,@supplierid,@status)
		set @err1=@@error
		fetch next from tempFinanceSummary into @amount,@tuikuan,@yongjin,@supplierid 
	end
	close tempFinanceSummary
	deallocate tempFinanceSummary
	--插入完成后，更新FinanceDetail表中的期数跟Status
	update FinanceDetail set Status=2, issue=@issue where status=1
	set @err2=@@error
	if (@err1>0 or @err2>0)
    Rollback Transaction
	else
	Commit Transaction
end
else if(@step=3) --财务结款中， 更新与期数对应FinanceDetail,FinanceSummary 表中的Status=3
begin
	Begin Transaction
	update FinanceSummary set status=3 where Issue=@Issue
	set @err1=@@error
	update FinanceDetail set status=3 where issue=@issue
	set @err2=@@error
	if(@err1>0 or @err2>0)
	Rollback Transaction
	else
	Commit Transaction 
end 
else if(@step=4)--财务结款完成，操作成功的话 对应FinanceDetail,FinanceSummary 表中的Status=4，操作失败就要更改FinanceDetail,FinanceSummary 表中的Status=2
	print ''
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FinanceLog_Get]    脚本日期: 04/09/2012 18:26:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-12-15>
-- 前台查看推广员的推广金额纪录
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_FinanceLog_Get] 
@memberid int,
@pagesize int,
@pageno int,
@flag varchar(100)=null,--查询
@begintime datetime=null,--查询开始时间
@endtime datetime=null,--查询结束时间
@currentFinance decimal(18,2) output,
@totalCount int output,
@totalPage int output,
@errorFlag int =null output,
@errormsg varchar(200)=null output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

select @currentFinance=finance from member(nolock)where memberid=@memberid

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' memberid='+ cast(@memberid as varchar(10)) 

--构造查询条件,暂时不用
--if isnull(@flag,0)<>0
--select @where=@where+' and flag='+cast(@flag as varchar(2))
--select @endtime =null
--select @begintime=null
--select @endtime=dateadd(day,1,@endtime)
--if @begintime is not null and @endtime is not null
--select @where =@where +' and addtime >='''+cast(@begintime as varchar(30)) +''' and addtime< '''+cast(@endtime as varchar(30))+''''
--else if  @begintime is not null
--select @where=@where+' and addtime>= '''+cast(@begintime as varchar(30))+''''
--else if  @endtime is not null
--select @where=@where+' and addtime< '''+cast(@endtime as varchar(30))+''''


select @sqlstr='select *from(
select *,Row_number() over(order by addtime desc) as rowno from xpfinancelog (nolock)
where ' + @where + ') as temp where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
insert log(content)values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by addtime desc) as rowno from xpfinancelog (nolock) where ' + @where + ')as tmep)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)
End Try
Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FinanceSummaries_SelectByFenYe]    脚本日期: 04/09/2012 18:26:51 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  procedure [dbo].[XpProc_FinanceSummaries_SelectByFenYe]
(
@pagerows int,        --每页行数    
@pageindex int,        --索引
@tab nvarchar(250),    --表名
@keyid nvarchar(50),    --主键
@total nvarchar(4000),    --条件
@sort nvarchar(50),    --排序
@kid nvarchar(500),    --列名
@tt  nvarchar(50), --针对获得总条数时需要的特殊条件，一般为*
@rows int output --总行数
)
as
begin
set nocount on
declare 
@befrows int,
@sql nvarchar(4000),
@sql2 nvarchar(4000)
set @befrows=@pagerows*(@pageindex-1)
--分页信息
set @sql='select top '+cast(@pagerows as nvarchar(50))+' '+@kid+' from '+@tab+' where '+@total+' and '+@keyid+' not in (select top '+cast(@befrows as nvarchar(50))+' '+@keyid+' from '+@tab+' where '+@total+' '+@sort+' )   '+@sort+''

--统计分页的汇总信息
set @sql2='select cast(sum(amount) as decimal(18,2)) as amount'+',cast(sum(TuiKuan) as decimal(18,2))  as TuiKuan'+',cast(sum(Yongjin) as decimal(18,2)) as Yongjin'+',cast(sum(amount)-sum(TuiKuan)-sum(YongJin) as decimal(18,2)) as ShiFu from'+'(select top '+cast(@pagerows as nvarchar(50))+' '+@kid+' from '+@tab+' where '+@total+' and '+@keyid+' not in (select top '+cast(@befrows as nvarchar(50))+' '+@keyid+' from '+@tab+' where '+@total+' '+@sort+' )   '+@sort+' )a'

EXEC (@sql)
EXEC (@sql2)
--print @sql
-------总条数------
set @sql=N'select @rows=count('+@tt+') from '+@tab+' where '+@total+'  '+''
exec sp_executesql @sql,N'@rows int out',@rows out
select  @rows
return @rows
end











GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FinanceSummariesStatistics_Select]    脚本日期: 04/09/2012 18:26:52 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--后台商家财务明细统计FinanceSummaries表的存储过程
CREATE  procedure [dbo].[XpProc_FinanceSummariesStatistics_Select]
(
@pagerows int,        --每页行数    
@pageindex int,        --索引
@total nvarchar(4000),    --条件
@rows int output --总行数
)
as
begin
set nocount on
declare 
@befrows int,
@sql nvarchar(4000)
set @befrows=@pagerows*(@pageindex-1)

--统计分页及汇总信息
--分页信息
--set @sql='select top '+cast(@pagerows as varchar(50))+' * 
--from (select financesummariesid, FinanceSummaries.Issue,Amount,TuiKuan,YongJin,(Amount-TuiKuan-YongJin)as ShiFu,Status,convert(varchar(10),StartTime,120)as StartTime,convert(varchar(10),EndTime,120)as EndTime,ROW_NUMBER() Over(order by FinanceSummaries.Issue desc)as rowid from FinanceSummaries,FinanceIssue where FinanceSummaries.Issue=FinanceIssue.Issue  and '+@total+')summaries
--where  summaries.rowid > ' +cast(@befrows as nvarchar(50)) 
--+'union all '+
----汇总信息
--'select  0,''总计'',sum(Amount),sum(TuiKuan),sum(YongJin),sum(ShiFu),0,null,null ,null from'+ 
--'(select top '+cast(@pagerows as varchar(50))+' * from (select financesummariesid, FinanceSummaries.Issue,Amount,TuiKuan,YongJin,(Amount-TuiKuan-YongJin)as ShiFu,Status,convert(varchar(10),StartTime,120)as StartTime,convert(varchar(10),EndTime,120)as EndTime,ROW_NUMBER() Over(order by FinanceSummaries.Issue desc)as rowid from FinanceSummaries,FinanceIssue where FinanceSummaries.Issue=FinanceIssue.Issue  and '+@total+')summaries  where  summaries.rowid > ' +cast(@befrows as nvarchar(50))
--+')a'
set @sql='select top '+cast(@pagerows as varchar(50))+' * 
from (select financesummariesid, FinanceSummaries.Issue,Amount,TuiKuan,YongJin,(Amount-TuiKuan-YongJin)as ShiFu,Status,ROW_NUMBER() Over(order by FinanceSummaries.Issue desc)as rowid from FinanceSummaries where '+@total+')summaries
where  summaries.rowid > ' +cast(@befrows as nvarchar(50)) 
+'union all '+
--汇总信息
'select  0,''总计'',sum(Amount),sum(TuiKuan),sum(YongJin),sum(ShiFu),0,null from'+ 
'(select top '+cast(@pagerows as varchar(50))+' * from (select financesummariesid, FinanceSummaries.Issue,Amount,TuiKuan,YongJin,(Amount-TuiKuan-YongJin)as ShiFu,Status,ROW_NUMBER() Over(order by FinanceSummaries.Issue desc)as rowid from FinanceSummaries where'+@total+')summaries  where  summaries.rowid > ' +cast(@befrows as nvarchar(50))
+')a'
insert log(content)values(@sql)
EXEC (@sql)

----print @sql
---------总条数------
set @sql=N'select @rows=count(*) from FinanceSummaries where '+@total+'  '+''
exec sp_executesql @sql,N'@rows int out',@rows out
select  @rows
return @rows
end

























GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FinanceSummary_Select]    脚本日期: 04/09/2012 18:26:53 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-09>
-- Description:	<用于商家后台，历史结款查询>
-- =============================================
CREATE  procedure [dbo].[XpProc_FinanceSummary_Select]
(
@pagerows int,        --每页行数    
@pageindex int,        --索引
@tab nvarchar(250),    --表名
@keyid nvarchar(50),    --主键
@total nvarchar(4000),    --条件
@sort nvarchar(50),    --排序
@kid nvarchar(500),    --列名
@tt  nvarchar(50), --针对获得总条数时需要的特殊条件，一般为*
@rows int output --总行数
)
as
begin
set nocount on
declare 
@befrows int,
@sql nvarchar(4000),
@sql2 nvarchar(4000)
set @befrows=@pagerows*(@pageindex-1)

--set @sql=
----分页信息
--'select * from (select top '+cast(@pagerows as nvarchar(50))+' '+@kid+' from '+@tab+' where '+@total+' and '+@keyid+' not in (select top '+cast(@befrows as nvarchar(50))+' '+@keyid+' from '+@tab+' where '+@total+' '+@sort+' )'+@sort+' )b  '
--+'union all '+
----统计分页的汇总信息
--'select null as issue, cast(sum(amount) as decimal(18,2)) as amount,cast(sum(TuiKuan) as decimal(18,2))  as TuiKuan'+',cast(sum(Yongjin) as decimal(18,2)) as Yongjin'+',-1 as status,null as supplierid,cast(sum(amount)-sum(TuiKuan)-sum(YongJin) as decimal(18,2)) as ShiFu,null,null from'+'(select top '+cast(@pagerows as nvarchar(50))+' '+@kid+' from '+@tab+' where '+@total+' and '+@keyid+' not in (select top '+cast(@befrows as nvarchar(50))+' '+@keyid+' from '+@tab+' where '+@total+' '+@sort+' )'+@sort+' )b  '

----分页信息
set @sql='select top '+cast(@pagerows as varchar(50))+' * 
from (select '+@kid+',ROW_NUMBER() Over(order by '+@keyid+' desc )as rowid from '+@tab+' where '+@total+')b
where  b.rowid > ' +cast(@befrows as nvarchar(50)) 
+'union all '+
----统计分页的汇总信息
'select null as issue, cast(sum(amount) as decimal(18,2)) as amount,cast(sum(TuiKuan) as decimal(18,2))  as TuiKuan'+',cast(sum(Yongjin) as decimal(18,2)) as Yongjin'+',-1 as status,null as supplierid,cast(sum(amount)-sum(TuiKuan)-sum(YongJin) as decimal(18,2)) as ShiFu,''本页合计'',null,null from'+
'(select top '+cast(@pagerows as varchar(50))+' * 
from (select '+@kid+',ROW_NUMBER() Over(order by '+ @keyid+' desc )as rowid from '+@tab+' where '+@total+')b
where  b.rowid > ' +cast(@befrows as nvarchar(50))+')a'
+' union all '+
----统计本次查询结果的汇总信息
'select null as issue, cast(sum(amount) as decimal(18,2)) as amount,cast(sum(TuiKuan) as decimal(18,2))  as TuiKuan'+',cast(sum(Yongjin) as decimal(18,2)) as Yongjin'+',-1 as status,null as supplierid,cast(sum(amount)-sum(TuiKuan)-sum(YongJin) as decimal(18,2)) as ShiFu,''本次查询合计'',null,null from'+
'(select * 
from (select '+@kid+',ROW_NUMBER() Over(order by '+ @keyid+' desc )as rowid from '+@tab+' where '+@total+')b'
+cast(@befrows as nvarchar(50))+')a'

--insert log(content)values(@sql)
--select * from log order by addtime desc
EXEC (@sql)
--print @sql
-------总条数------
set @sql=N'select @rows=count('+@tt+') from '+@tab+' where '+@total+'  '+''
exec sp_executesql @sql,N'@rows int out',@rows out
select  @rows
return @rows
end
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FinanceSummaryStatistics_Select]    脚本日期: 04/09/2012 18:26:54 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
--后台商家财务明细统计存储过程
CREATE  procedure [dbo].[XpProc_FinanceSummaryStatistics_Select]
(
@pagerows int,        --每页行数    
@pageindex int,        --索引
@total nvarchar(4000),    --条件
@rows int output --总行数
)
as
begin
set nocount on
declare 
@befrows int,
@sql nvarchar(4000)
--@sql2 nvarchar(4000)
set @befrows=@pagerows*(@pageindex-1)
--declare @temptab table(financesummaries int ,issue varchar(50),amount money,tuikuan money,yongjin money,status int, rowid int)


----分页信息
--set @sql='select top '+cast(@pagerows as nvarchar(50))+' * into ##temp from (select '+@kid+',ROW_NUMBER() Over('+ @sort +' )as rowid from '+@tab+' )summary where '+@total+' and summary.rowid >' +cast(@befrows as nvarchar(50))
----统计分页的汇总信息
----set @sql2='select cast(sum(amount) as decimal(18,2)) as amount'+',cast(sum(TuiKuan) as decimal(18,2))  as TuiKuan'+',cast(sum(Yongjin) as decimal(18,2)) as Yongjin'+',cast(sum(amount)-sum(TuiKuan)-sum(YongJin) as decimal(18,2)) as ShiFu from'+'(select top '+cast(@pagerows as nvarchar(50))+' '+@kid+' from '+@tab+' where '+@total+' and '+@keyid+' not in (select top '+cast(@befrows as nvarchar(50))+' '+@keyid+' from '+@tab+' where '+@total+' '+@sort+' )   '+@sort+' )a'
--set @sql2='select  a.*,b.SupplierName,b.BankNo from (select isnull(financesummaryid,'''')as financesummaryid ,case when grouping(financesummaryid)=1 and grouping(issue)=1 and grouping(status)=1 and grouping(supplierid)=1 then '+'''总计'''+' else issue end issue,case when grouping(financesummaryid)=1 and grouping(issue)=1 and grouping(status)=1 and grouping(supplierid)=1 then '+''''''+' else status end status,sum(amount) as amount,sum(tuikuan)as tuikuan,sum(yongjin)as yongjin,sum(amount)-sum(tuikuan)-sum(yongjin) as shifu ,supplierid from ##temp  group by financesummaryid,issue,status,supplierid with rollup )a left join supplier b on a.supplierid=b.supplierid where  financesummaryid is not null and a.issue is not null  and a.supplierid is not null and a.status is not null or a.issue='+'''总计'''+'order by financesummaryid desc'

set @sql=
----分页信息
'select top '+cast(@pagerows as nvarchar(50))+' *   from'+ 
'(select  FinanceSummary.*,Supplier.SupplierName,bankno,(Amount-TuiKuan-YongJin)as ShiFu,ROW_NUMBER() Over(order by Issue desc  )as rowid 
from FinanceSummary,supplier where FinanceSummary.supplierid=supplier.supplierid and'+@total+' )summary 
where  summary.rowid > ' +cast(@befrows as nvarchar(50)) 
+' union all '+
----统计分页的汇总信息
'select 0,''合计'',sum(amount),sum(tuikuan),sum(yongjin),0,null,null,null,null,sum(shifu),null from' +
'(select top '+cast(@pagerows as nvarchar(50))+' *   from'+ 
'(select  FinanceSummary.*,Supplier.SupplierName,bankno,(Amount-TuiKuan-YongJin)as ShiFu,ROW_NUMBER() Over(order by Issue desc  )as rowid 
from FinanceSummary,supplier where FinanceSummary.supplierid=supplier.supplierid and '+@total+' )summary 
where  summary.rowid > ' +cast(@befrows as nvarchar(50)) +')a'

--insert log(content)values(@sql)
EXEC (@sql)
--EXEC (@sql2)
--print @sql
-------总条数------
set @sql=N'select @rows=count(*) from FinanceSummary where '+@total+'  '+''
exec sp_executesql @sql,N'@rows int out',@rows out
select  @rows
return @rows
end


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FlashAD_Add]    脚本日期: 04/09/2012 18:26:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-11-25>
-- Description:	<添加幻灯片广告>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_FlashAD_Add] 
@title varchar(50),--广告标语
@img varchar(50),--广告图片名
@folder varchar(50),--图片路径
@link varchar(200),--图片链接
@supplierid int,--所属商家
@catid int,--所属分类
@sort int,--排序
@status int,--状态
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''
Begin Try
insert into FlashAD (FlashName,FlashImg,FlashLink,Sort,ADCategoryID,Status,Folder,SupplierID) 
values 
(@title,@img,@link,@sort,@catid,@status,@folder,@supplierid)
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END








GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FlashAD_Update]    脚本日期: 04/09/2012 18:26:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-11-25>
-- Description:	<更新幻灯片广告>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_FlashAD_Update] 
@flashid int,--广告ID
@title varchar(50),--广告标语
@img varchar(50),--广告图片名
@folder varchar(50),--图片路径
@link varchar(200),--图片链接
@supplierid int,--所属商家
@catid int,--所属分类
@sort int,--排序
@status int,--状态
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''
Begin Try
update FlashAD
set FlashName=@title,
FlashImg=@img,
FlashLink=@link,
Sort=@sort,
ADCategoryID=@catid,
Status=@status,
Folder=@folder,
SupplierID=@supplierid
where flashid=@flashid
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END








GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FlashADSort_Update]    脚本日期: 04/09/2012 18:26:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-11-25>
-- Description:	<更新幻灯片广告排序>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_FlashADSort_Update] 
@ids varchar(8000),
@sorts varchar(8000),
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorFlag=0,@errorMsg=''
Begin Try
insert into log(content)values(@ids)
insert into log(content)values(@sorts)
select * into #d from SplitToTable_Func(@ids,',')
select * into #s from SplitToTable_Func(@sorts,',')
select d.value as flashid,s.value as sort
into #t
from #d d
left join #s s on d.id=s.id

update f set f.sort=t.sort
from flashad f,#t t
where f.flashid=t.flashid
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END







GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Floor_Add]    脚本日期: 04/09/2012 18:26:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-08-28>
-- Description:	<添加楼层商品>

-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Floor_Add]
@FloorName	varchar(50),--楼层名称
@catid int=null,--所属大类
@TopAD varchar(1000),--左侧广告
@ContentAD varchar(1000),--正文广告
@Backgroundimage varchar(100),--楼层顶部广告
@Sort int,--楼层位置
@Status	int,--是否显示
@SupplierID int,--商家ID
@pids	varchar(1000),--商品ID连接字符串
@gids varchar(1000),--货品ID连接字符串
@sorts varchar(1000),--排序连接字符串
@errorFlag int output,--错误标志
@errorMsg varchar(200)output --错误信息
AS
BEGIN
Begin Try
begin tran
select * into #t1 from SplitToTable_Func(@pids,',')
--select * into #t2 from SplitToTable_Func(@gids,',')
select * into #t3 from SplitToTable_Func(@sorts,',')

--
--select 0 as floorid, t1.value as productid, t2.value as goodsid,t3.value as sort
--into #t
--from #t1 t1,#t2 t2,#t3 t3
--where t1.id=t2.id and t1.id=t3.id

select 0 as floorid, t1.value as productid,t3.value as sort
into #t
from #t1 t1,#t3 t3
where t1.id=t3.id

-- 插入套装主体信息
INSERT [floor](floorName,CatID, TopAD, ContentAD, Backgroundimage, Sort, Status,SupplierID)
VALUES (@floorName,@CatID, @TopAD, @ContentAD, @Backgroundimage, @Sort,@Status,@SupplierID)

--获取刚添加的楼层ID
declare @floorid int
select @floorid=@@IDENTITY

--更改临时表中的楼层ID
update #t set floorid=@floorid
--插入楼层商品
insert into floorpdt(floorid,productid,sort)
select * from #t order by sort asc
select @errorflag=0,@errormsg='操作成功'
commit tran
End Try

Begin Catch
rollback tran
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
end Catch
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Floor_Delete]    脚本日期: 04/09/2012 18:26:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-10-26>
-- Description:	<删除楼层信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Floor_Delete]
@floorid int,
@supplierid int,--商家ID
@errorflag int out,--错误标志
@errormsg varchar(200) out--错误信息描述
AS
BEGIN
if not exists(select *from [floor] (nolock) where floorid=@floorid and supplierid=@supplierid)
begin
set @errorflag=1
set @errorMsg='要删除的楼层不存在，删除失败'
return
end
Begin Try
begin tran
select * into #s from SplitToTable_Func(@floorid,',')
--删除楼层的主体信息
delete [floor] from [floor](nolock),#s where [floor].floorid=#s.value

--删除套装主体信息
--delete from suit where suitid=@suitid
delete floorPdt from floorPdt(nolock) ,#s where floorPdt.floorid=#s.value
set @errorflag=0
set @errorMsg='删除成功'
commit tran
End Try

Begin Catch
-- 捕捉错误
rollback tran
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END








GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Floor_Get]    脚本日期: 04/09/2012 18:26:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-11-15>
-- Description:	<橱窗列表>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Floor_Get] 
@sid int=0,--商家ID
@cid int=-1,--分类ID
@errorFlag int=null output,--错误标志
@errorMsg varchar(200)=null output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''
Begin Try
SELECT * FROM [Floor] where SupplierID=@sid and CatID=case when @cid=-1 then CatID else @cid end ORDER BY sort 
End Try
Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Floor_Update]    脚本日期: 04/09/2012 18:26:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-10-26>
-- Description:	<更新楼层信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Floor_Update]
@FloorID int,
@FloorName	varchar(50),--楼层名称
@catid int=null,--所属大类
@TopAD varchar(1000),--左侧广告
@ContentAD varchar(1000),--正文广告
@Backgroundimage varchar(100),--楼层顶部广告
@Sort int,--楼层位置
@Status	int,--是否显示
@SupplierID int,--商家ID
@pids	varchar(1000),--商品ID连接字符串
@gids varchar(1000),--货品ID连接字符串
@sorts varchar(1000),--排序连接字符串
@errorFlag int output,--错误标志
@errorMsg varchar(200)output --错误信息

AS
BEGIN
Begin Try
begin tran
select * into #t1 from SplitToTable_Func(@pids,',')
--select * into #t2 from SplitToTable_Func(@gids,',')
select * into #t2 from SplitToTable_Func(@sorts,',')

--select floorid=@floorid, t1.value as productid, t2.value as goodsid,t3.value as sort
--into #t
--from #t1 t1,#t2 t2,#t3 t3
--where t1.id=t2.id and t1.id=t3.id
select floorid=@floorid, t1.value as productid, t2.value as sort
into #t
from #t1 t1,#t2 t2
where t1.id=t2.id
-- 更新套装主体信息
update [floor]
set floorname=@FloorName, 
CatID=@catid,
TopAD=@TopAD, 
ContentAD=@ContentAD, 
Backgroundimage=@Backgroundimage, 
Sort=@Sort, 
Status=@Status
where floorid=@floorid

--删除旧的套装明细
delete from floorPdt where floorid=@floorid

--插入新的套装明细
insert into floorpdt(floorid,productid,sort)
select * from #t order by sort asc
select @errorflag=0,@errormsg='更新成功'
commit tran
End Try
Begin Catch
rollback tran
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return 0
End Catch
END






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FloorAndPdt_Get]    脚本日期: 04/09/2012 18:27:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-11-15>
-- Description:	<查找不同频道对应的橱窗列表及相关商品信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_FloorAndPdt_Get] 
@sid int=0,--商家ID
@cid int=-1,--分类ID
@errorFlag int=null output,--错误标志
@errorMsg varchar(200)=null output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''
Begin Try
--厨窗基本设置
select FloorID,FloorName,TopAD,ContentAD,Backgroundimage,Sort,Status
into #f
from [floor](nolock) 
where supplierid=@sid and CatID=@cid and status=1 
order by sort asc
--厨窗推荐产品
select fp.FloorID,fp.ProductID,fp.GoodsID,fp.Sort,ImgFolder,ProductImg,thumbnailimg,productname,marketprice,isnull(l.pmtprice,p.memberprice) as memberprice,case when g.subtype='limittime' then 16 when g.subtype='specialprice' then 2 when g.subtype='coupon' then 10 when PiEndTime>getdate() then PiNo else 0 end as PiNo 
from product p(nolock),#f f,floorpdt fp(nolock)
left join PmtGoodsList l(nolock) on fp.productid=l.productid
where f.floorid=fp.floorid and fp.productid=p.productid
End Try
Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_FloorRelatedInfo_Get]    脚本日期: 04/09/2012 18:27:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-10-26>
-- Description:	<获取楼层相关信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_FloorRelatedInfo_Get]
@supplierid int,--商家ID
@floorid int, --楼层ID
@pids varchar(1000) output,--用逗号分隔的productid
@errorFlag int output,
@errorMsg varchar(200) output
AS
BEGIN
--insert log(content)values(@floorid)
--insert log(content)values(@supplierid)
select @errorFlag=0
select @errorMsg=''
--获取楼层的基本信息
if not exists(select * from floor(nolock) where floorid=@floorid and supplierid=@supplierid)
begin
select @errorFlag=1
select @errorMsg='楼层信息不存在'
return
end
select *
from floor(nolock) 
where floorid=@floorid and supplierid=@supplierid

--获取楼层的商品明细信息
select fp.floorid,fp.productid,fp.goodsid,p.productname,fp.sort,p.imgfolder,p.productimg,p.thumbnailimg
from floorpdt fp(nolock),product p(nolock)
where  fp.floorid=@floorid and fp.productid=p.productid

select @pids=''
select @pids=@pids+','+cast(productid as varchar) 
from floorpdt(nolock) 
where floorid=@floorid
select @pids=stuff(@pids,1,1,'')
--insert log(content)values(@pids)
END








GO
/****** 对象:  StoredProcedure [dbo].[XpProc_GetShopSettingBySid]    脚本日期: 04/09/2012 18:27:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<取得供应商店铺首页的一些基本设置>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_GetShopSettingBySid]
@sid int,--供应商ID
@topnum int =10--热销商品，最新商品的显示数量
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	--供应商的基本信息
	select SupplierName,SupplierID,Logo,Description,Address, AddTime,Banner,ContactInfo,PdtNum,Reviews,pj1,pj2,pj3,pj4,pj5,PingFen,TopAD,Template from Supplier(nolock) where supplierid=@sid
	--供应商产品一级分类
	select cid ,cname from subcategory(nolock) where sid=@sid and depth=1  order by sort
	--供应商所有产品的分类
	select * into #ssc from subcategory(nolock) where sid=@sid
	select s1.sid,s1.depth,s1.cid as cid,s1.cname as cname,s1.logo as logo,s1.stype,s1.childs as childs,isnull(s2.sort,s1.sort) as ssort,left(s1.cid,2)
	as cno from #ssc s1 left join #ssc s2 on s1.parentid=s2.cid order by ssort,cno,s1.depth,s1.sort,cid
--	select * into #ssc from subcategory where sid=@sid
--	select s1.*,isnull(s2.sort,s1.sort) as ssort,left(s1.cid,2) as cno from #ssc s1 left join #ssc s2 on s1.parentid=s2.cid order by ssort,cno,depth,sort,cid
	--供应商热销产品
	select top (@topnum) productid,productname,thumbnailimg ,salenum,marketprice,memberprice,ImgFolder,ProductImg,dbo.f_GetCategoryNo(CategoryID) As CategoryNo from product(nolock) where Status = 1 and IsForSale =1 and IsPackaged = 0  and supplierid= (@sid) order by salenum desc
	--供应商最新产品
	select top (@topnum) productid,productname,thumbnailimg ,addtime ,marketprice,memberprice,ImgFolder,ProductImg from product(nolock) where Status = 1 and IsForSale =1 and IsPackaged = 0 and supplierid= (@sid) order by Addtime desc
	--厨窗基本设置
	select FloorID,FloorName,TopAD,ContentAD,Backgroundimage,Sort,Status from [floor] nolock where supplierid=@sid and status=1 order by sort asc
	--厨窗推荐产品
	select fp.FloorID,fp.ProductID,fp.GoodsID,fp.Sort,ImgFolder,ProductImg,thumbnailimg,productname,marketprice,memberprice from [floor] f(nolock),floorpdt fp(nolock),product p(nolock)where f.supplierid=@sid and f.floorid=fp.floorid and f.status=1 and fp.productid=p.productid
	--导航栏
	select NavBarName,Link,Target,Inside from NavBar where supplierid=@sid order by Sort asc
	--幻灯片广告
	select FlashName,FlashImg,FlashLink,Folder from FlashAD where status=1 and supplierid=@sid
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_GetSubCategory_Path]    脚本日期: 04/09/2012 18:27:02 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE procedure [dbo].[XpProc_GetSubCategory_Path] --得到分类的导航，格式为：所有商品>>一级分类>>二级分类
@cid varchar(20),--分类ID
@sid int,--所属供应商的ID
@result nvarchar(300) out
as
begin
	declare @tmpcid nvarchar(20)
	declare @tmpcname nvarchar(20)
	declare @catno nvarchar(20)
	set @result='<a href='+'default.aspx?sid='+cast(@sid as varchar(10))+'&act=list>'+'所有商品'+'</a>'
	declare mycursor cursor 
	for
	select cid,cname
	from SubCategory c(nolock)
	where 
	left(@cid,len(cid))=cid and sid=@sid
	order by len(cid)
	open mycursor
	fetch next from mycursor into @tmpcid,@tmpcname
	while @@fetch_status = 0
	begin
		set @result = @result+ '>><a href='+'default2.aspx?sid='+cast(@sid as varchar(10))+'&act=list&cid='+@tmpcid+'>'+@tmpcname+'</a>'
		fetch next from mycursor into @tmpcid,@tmpcname
	end
	close mycursor        
	deallocate mycursor 
insert [log]([content])values(cast(@cid as varchar)+' s'+cast(@result as varchar(330)))
select *from [log] order by addtime
end


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Gift_Add]    脚本日期: 04/09/2012 18:27:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[XpProc_Gift_Add](
@productNo NVarChar(50),
@giftName VarChar(100),
@score Int,
@storage Int,
@LimitedNumber Int,
@catID varchar(20),
@errorFlag int output,
@errorMsg varchar(100) output
)
as
begin
declare @pid int
select @pid=productID from product(nolock) where productno=@productNo
if(@pid is  null)
begin
	set @errorFlag=1
	set @errorMsg='产品不存在，请重新输入商品编号'
	return
end
else
begin 
begin try
begin tran
	INSERT INTO Gift (GiftName,ProductID,ProductNo,Score,Storage,CatID,LimitedNumber) VALUES (@giftName,@pid,@productNo,@Score,@storage,@catID,@LimitedNumber)
	update GiftCat set GiftNum= isnull(GiftNum,0)+1 from giftcat(nolock) where catid=@catid
	set @errorFlag=0
	set @errorMsg='成功添加礼品'
commit tran
end try
begin catch
	rollback
	set @errorFlag=1

	set @errorMsg='添加礼品失败'
end catch
end
end




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Gift_Delete]    脚本日期: 04/09/2012 18:27:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[XpProc_Gift_Delete](
@giftID int,
@errorFlag int output,
@errorMsg varchar(100) output
)
as

begin 
declare @catid varchar(20)
select @catid=catid from gift where giftid=1111
begin try
begin tran
	delete from gift where giftid=@giftid
	update giftcat set giftnum=giftnum-1 where catid=@catid
	set @errorFlag=0
	set @errorMsg='成功删除礼品'
commit tran
end try
begin catch
	rollback
	set @errorFlag=1

	set @errorMsg='删除礼品失败'
end catch
end






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Gift_Path]    脚本日期: 04/09/2012 18:27:03 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE procedure [dbo].[XpProc_Gift_Path]
@cid varchar(20),--分类ID
@result nvarchar(300) out
as
begin
	begin
		declare @catid varchar(20)
		declare @catname varchar(20)
		set @result = '<a href="/index.html">首页</a> ><a href="/Gifts.html">全部礼品</a> > '
		declare mycursor cursor 
		for
		select CatID,CatName from giftcat where left(@cid,len(catid))=catid 
		open mycursor
		fetch next from mycursor into @catid,@catname
		while @@fetch_status = 0
		begin
			begin
				set @result = @result + '<a href="/gifts-' + cast(@catid as varchar(20)) + '.html">' + rtrim(@catname) + '</a> > '
			end
			fetch next from mycursor  into @catid,@catname
		end
		close mycursor        
		deallocate mycursor 
	end
	select @result=left(@result,len(@result)-2)
end






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Gift_Update]    脚本日期: 04/09/2012 18:27:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[XpProc_Gift_Update](
@giftID int ,
--@goodsNo NVarChar(50),
@productNo NVarChar(50),
@giftName VarChar(100),
@score Int,
@storage Int,
@LimitedNumber Int,
@catID varchar(20),
@errorFlag int output,
@errorMsg varchar(100) output
)
as
begin
declare @pid int,@oldcatid varchar(20)
select @pid=productID from product(nolock) where productNo=@productNo
select @oldcatid=catid from gift(nolock) where giftid=@giftid


if(@pid is  null)
begin
	set @errorFlag=1
	set @errorMsg='产品不存在，请重新输入商品编号'
	return
end
else
begin
begin try
begin tran
	UPDATE Gift Set GiftName=@GiftName, ProductID=@pid,productNo=@productNo,Score=@score,Storage=@storage,LimitedNumber=@LimitedNumber ,CatID=@catID Where GiftID = @giftID
	if(@oldcatid<>@catid)
	begin
	update giftcat set GiftNum=case when (isnull(GiftNum,0)-1)<0 then 0 else isnull(GiftNum,0)-1 end  from giftcat(nolock)where catid=@oldcatid
	update giftcat set GiftNum=isnull(GiftNum,0)+1 from giftcat(nolock)where catid=@catid
	end
	set @errorFlag=0
	set @errorMsg='成功修改礼品'
commit tran
end try
begin catch
	rollback
	set @errorFlag=1
	set @errorMsg='修改礼品失败'
end catch
end
end



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_GiftCanExchageNum_Count]    脚本日期: 04/09/2012 18:27:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-07-29>
-- Description:	<会员还可以兑换的礼品数量的统计>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_GiftCanExchageNum_Count] 
@cartid varchar(36),--购物车ID
@memberid int,--会员ID
@gid int,--礼品ID
@canexchangenum int output--还可兑换数量,返回999999999为不限制兑换数量
AS
BEGIN
declare @exchagednum int--历史兑换数量

--统计会员历史兑换数量
select @exchagednum=sum(quantity)
from gift g(nolock),MemberExchangeGifts m(nolock)
where g.giftid=@gid and g.productid=m.productid and m.memberid=@memberid
--计算还可以兑换的数量
select @canexchangenum=case when isnull(g.Limitednumber,0)=0 then 999999999 else g.Limitednumber-isnull(@exchagednum,0)-isnull(s.quantity,0) end
from gift g(nolock)
left join shoppingcart s(nolock) on g.productid=s.productid and s.ptype=2 and s.cartid=@cartid
where g.giftid=@gid 
select @canexchangenum
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_GiftList_Select]    脚本日期: 04/09/2012 18:27:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[XpProc_GiftList_Select](
@cid varchar(20)=null,--礼品的分类ID
@lowScore int =null,--查找条件，兑换积分
@hightScore int =null,--查找条件，兑换积分
@pageSize int =12,--每页显示的礼品数
@pageNo int=1,--页码
@sort varchar(50)=null,--排序字段
@position varchar(300)=null output, --当前位置
@totalpage int=null output,--总页数
@totalcount int=null output,--总记录数
@errorflag int=null output,
@errormsg varchar(200)=null output
)
as
begin
set nocount on

select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where ='1=1' 

if isnull(@cid,0)<>'0'
select @where=@where+' and catid like '''+@cid+'%'''
if isnull(@lowScore,0)<>0
select @where=@where+' and g.score >= '+convert(varchar(20),@lowScore)
if isnull(@hightScore,0)<>0
select @where=@where+' and g.score <= '+convert(varchar(20),@hightScore)
select @sort=isnull(@sort,'order by GiftID')


select @sqlstr='select GiftID, GiftName,catid,Score,imgfolder,ThumbnailImg,AlreadyExchaged from(
select GiftID, GiftName,catid,g.Score,imgfolder,p.ThumbnailImg,AlreadyExchaged,Row_number() over('+@sort+') as rowno 
from product p(nolock),gift g(nolock)
where p.productid=g.productid and '
+ @where + ') as temp where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
print @sqlstr
--insert log(content)values(@sort)

--获取分页商品datatable[1]
Execute(@sqlstr)


--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over('+@sort+') as rowno from product p(nolock),gift g(nolock)
where p.productid=g.productid and ' + @where + ') as temp)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

select @totalcount=isnull(@totalcount,0)
select @totalpage=ceiling(@totalcount*1.0 / @pagesize)

--兑换排行
Select top 10 GiftID,GiftName From Gift(nolock) Order By AlreadyExchaged Desc

--礼品分类
select catid,catname,parent from GiftCat(nolock) where parent is null order by catid

--礼品页导航条
exec XpProc_gift_path @cid,@position output
end
--begin
--declare @catid varchar(20)
--declare @catname varchar(20),@result varchar(8000)
--	set @result = '<a href="/index.html">首页</a> ><a href="/Gifts.html">全部礼品</a> > '
--	declare mycursor cursor 
--	for
--	select CatID,CatName from giftcat where left(@cid,len(catid))=catid 
--	open mycursor
--	fetch next from mycursor into @catID,@catname
--	while @@fetch_status = 0
--	begin
--		begin
--			set @result = @result + '<a href="/gifts-' + cast(@catID as varchar(20)) + '.html">' + rtrim(@catname) + '</a> > '
--		end
--		fetch next from mycursor  into @catID,@catname
--	end
--	close mycursor        
--	deallocate mycursor 
--end
--select @position=left(@result,len(@result)-2)
--end
--@TableName varchar(500),    --表名
--@Fields varchar(5000) = '*',   --字段名(全部字段为*)
--@OrderField varchar(5000),    --排序字段(必须!支持多字段)
--@sqlWhere varchar(5000) = Null, --条件语句(不用加where)
--@pageSize int,       --每页多少条记录
--@pageIndex int = 1 ,     --指定当前为第几页
--@totalRecord int = 0,     --总记录数
--@totalPage int output     --返回总页数
--)
--as
--begin
--Begin tran --开始事务
--   declare @sql nvarchar(4000);
--   if @totalRecord<=0 
--   begin
--    --计算总记录数
--    if (@SqlWhere='' or @sqlWhere=null)
--     set @sql = 'select @totalRecord = count(*) from ' + @TableName
--    else
--     set @sql = 'select @totalRecord = count(*) from ' 
--        + @TableName + ' with(nolock) where ' + @sqlWhere
--    exec sp_executesql @sql,N'@totalRecord int output',@totalRecord output--计算总记录数    
--   end
--   --计算总页数
--   select @TotalPage=ceiling((@totalRecord+0.0)/@PageSize)
--   if (@SqlWhere='' or @sqlWhere=NULL)
--    set @sql = 'select * from (select row_number() over(order by ' + @OrderField 
--       + ') as rowId,' + @Fields + ' from ' + @TableName
--   else
--   set @sql = 'select * FROM (select row_number() over(order by ' + @OrderField 
--      + ') as rowId,' + @Fields + ' from ' + @TableName + ' with(nolock) where ' 
--      + @SqlWhere
--   --处理页数超出范围情况
--   if @PageIndex<=0
--    set @pageIndex = 1
--   if @pageIndex>@TotalPage
--    set @pageIndex = @TotalPage
--   --处理开始点和结束点
--   declare @StartRecord int
--   declare @EndRecord int
--   set @StartRecord = (@pageIndex-1)*@PageSize + 1
--   set @EndRecord = @StartRecord + @pageSize - 1
--   --继续合成sql语句
--   set @Sql = @Sql + ') as t where rowId between ' + Convert(varchar(50),@StartRecord) 
--      + ' and ' + Convert(varchar(50),@EndRecord)
--   print @sql
--   exec(@Sql)
--   ---------------------------------------------------
--If @@Error <> 0
--begin
--	rollBack tran
--	return -1
--end
--else
--begin
--	commit tran
--	return @totalRecord ---返回记录总数
--end
--end
--begin
----礼品分类
--select catid,catname from GiftCat where status=1
----分页数据
--select giftname,Product.ThumbnailImg,productImg ,gift.score from gift,product where gift.productid=product.productid
--
--end
--
----搜索条件
----积分，catid, alreadyexchanged,score



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_GiftRelateInfo_Get]    脚本日期: 04/09/2012 18:27:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas>
-- Create date: <2011-07-25>
-- Description:	<获取礼品详细页面的相关的信息>
-- Debug: exec XpProc_GiftRelateInfo_Get 437
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_GiftRelateInfo_Get]
@giftID int ,--礼品ID
@position varchar(300)=null output --当前位置
AS
BEGIN
--从礼品中得到商品ID
declare @pid int
select @pid=productid from gift where giftid=@giftID

--礼品详情  datatable[0]
select GiftID,GiftName,gift.ProductID,gift.ProductNo,gift.Score,gift.Storage,AlreadyExchaged,LimitedNumber,ExchagedMembers,Description,
PackingList,AfterService,Spec,SpecDesc,SkuMap,catid from gift(nolock),product(nolock)where giftid=@giftid and gift.productid=product.productid 

--礼品的相关图片 datatable[1] img1为原图，img2为300*300 img6为50*50
select img1,img2,img6,imgfolder from pdtimg(nolock) where pid=@pid order by sort

--积分兑换排行榜 datatable[3]
Select top 10 GiftID,GiftName From Gift(nolock) Order By AlreadyExchaged Desc

--礼品页导航条
declare @cid varchar(20)
select @cid=catid from gift where giftid=@giftid
exec XpProc_gift_path @cid,@position output
end










GO
/****** 对象:  StoredProcedure [dbo].[XpProc_GoodsName_Update]    脚本日期: 04/09/2012 18:27:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-08-06>
-- Description:	<更新货品名称>
-- =============================================
create PROCEDURE [dbo].[XpProc_GoodsName_Update]
AS
BEGIN

Begin Try
begin tran
--统一把货品名称重置为主商品名称
update g set g.goodsname=p.productname
from product p,goods g
where p.productid=g.productid
--更新有2个规格项的货品名称
select goodsid,goodsname,propsdesc,
substring(propsdesc,1,charindex(';',propsdesc)-1) as prop1,
substring(propsdesc,charindex(';',propsdesc)+1,len(propsdesc)) as prop2
into #g
from goods 
where charindex(';',propsdesc)>0
update #g set goodsname=goodsname+' '+substring(prop1,charindex(':',prop1)+1,len(prop1))+' '+substring(prop2,charindex(':',prop2)+1,len(prop2))
update g set g.goodsname=gg.goodsname from goods g,#g gg where g.goodsid=gg.goodsid and charindex(';',g.propsdesc)>0
--更新只有一个规格项的货品名称
update goods set goodsname=goodsname+' '+substring(propsdesc,charindex(':',propsdesc)+1,len(propsdesc))
where charindex(';',propsdesc)=0
commit
End Try

Begin Catch
-- 捕捉错误
rollback
End Catch
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_GoodsSearch_Get]    脚本日期: 04/09/2012 18:27:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-05-21>
-- Description:	<管理后台,手动添加订单时搜索商品>
-- Debug:
/*
declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
declare @key varchar(100),@cid varchar(20),@subcat varchar(20),@bid varchar(20),@pids varchar(2000),@productno varchar(20),@status int,@lowprice decimal(18,2),@highprice decimal(18,2),@lowstock int,@highstock int,@starttime varchar(50),@endtime varchar(50),@tag varchar(100),@supplierid int,@pagesize int,@pageno int
select @key='',@cid='-1',@subcat='-1',@bid='-1',@pids='',@productno='',@status=1,@lowPrice=0,@highprice=0,@lowstock=0,@highstock=0,@starttime='',@endtime='',@tag='',@supplierid=0,@pagesize=15,@pageno=1
exec XpProc_PdtSearch_Get @key,@cid,@subcat,@bid,@pids,@productno,@status,@lowPrice,@highprice,@lowstock,@highstock,@starttime,@endtime,@tag,@supplierid,@pagesize,@pageno,@totalpage output,@totalcount output,@errorflag output,@errormsg output
select @totalpage,@totalcount,@errorflag,@errormsg
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_GoodsSearch_Get]
@searchType int =null,--搜索类型,1按商品编号，1按商品名字，2按商品关键字
@keyword varchar(100)=null,--关键字
@cid varchar(20)=null,--主分类
@subcat varchar(20)=null,--店内分类
@bids varchar(8000)=null,--品牌ID
@pids varchar(8000)=null,--逗号分隔的商品ID字符串
@productno varchar(20)=null,--商品编号
@isdel int=null,--商品是否已删除 0未删除 1已删除 -1 不限
@status int=null,--是否是已审核的商品，0未审核  1已审核 -1审核不过 -2不限
@isForSale int=null,--是否是上架的商品，0不是 1是 -1不限
@lowprice decimal(18,2)=null,--价格区间下限
@highprice decimal(18,2)=null,--价格区间上限
@lowstock int=null,--库存区间下限
@highstock int=null,--库存区间上限
@starttime varchar(50)=null,--添加时间下限
@endtime varchar(50)=null,--添加时间上线
@tag varchar(100)=null,--标签
@supplierid int=0,--是否搜索运营商自已的商品，-2查找所有的商家的商品，-1查找非自营的商品 0查找自营商品 其它值就是查找对应的商家
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码,
@totalpage int output,--总页数
@totalcount int output,--总记录数
@errorflag int output,
@errormsg varchar(200) output

AS
BEGIN
set nocount on
--declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0
Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = 'p.supplierid = '+convert(varchar(20),@supplierid)

if isnull(@cid,'0')<>'0' --0代表所有的类别
select @where=@where+' and categoryno like '''+convert(varchar(50),dbo.f_GetCategoryNo(@cid))+'%'''

if isnull(@bids,'0')<>'0'
select @where=@where+' and brandid  in('+@bids+') '

if isnull(@productno,'')<>''
select @where=@where+' and productno = '+@productno

if isnull(@isdel,-1)<>-1
select @where=@where+' and isdel = '+convert(varchar(10),@isdel)

if isnull(@status,-2)<>-2
select @where=@where+' and status = '+convert(varchar(10),@status)

if isnull(@isForSale,-1)<>-1
select @where=@where+' and isForSale = '+convert(varchar(10),@isForSale)

if isnull(@lowprice,0)<>0
select @where=@where+' and g.memberprice >= '+convert(varchar(20),@lowprice)

if isnull(@highprice,0)<>0
select @where=@where+' and g.memberprice <= '+convert(varchar(20),@highprice)

if isnull(@lowstock,0)<>0
select @where=@where+' and g.storage >= '+convert(varchar(20),@lowstock)

if isnull(@highstock,0)<>0
select @where=@where+' and g.storage <= '+convert(varchar(20),@highstock)

if isnull(@starttime,'')<>''
select @where=@where+' and g.addtime >='''+@starttime+''''

if isnull(@endtime,'')<>''
select @where=@where+' and g.addtime <='''+@endtime+''''

if isnull(@pids,'')<>''
select @where=@where+' and g.productid in (' + @pids + ')'

if isnull(@subCat,'0')<>'0'
select @where=@where+' and p.subcategoryid like'''+@subcat+'%'''

--按搜索类型查找商品
declare @temp varchar(1000)
select @temp=''
if isnull(@keyword,'')<>''
begin
	if isnull(@searchType,0)<>0
	begin
	select @temp=case @searchType when '1' then ' and ProductNo like ''%' when '2' then ' and productname like ''%' when '3' then ' and Keyword like ''%' end
	select @where=@where+@temp+ @keyword+'%'''
	end
	else
	begin
	select @temp= ' AND (ProductName Like ''%' + @keyword + '%'' or ProductNo Like ''%' + @keyword + '%'' or Keyword Like ''%' + @keyword + '%'')'
	select @where=@where+@temp 
	end
end
--if isnull(@key,'')<>''
--select @where=@where+' and productname like ''%' + @key + '%'''
select @sqlstr='select *from(select g.ProductID,isnull(GoodsName,ProductName)as ProductName,ProductNo,CategoryID,BrandID,g.MemberPrice,ProductImg,ImgFolder,GoodsID,GoodsNo,PropsDesc,g.Storage,MiniBuyNum,p.Score,Row_number() over(order by g.goodsid desc) as rowno 
from product p(nolock) left join goods g(nolock) on p.productid=g.productid
where ' + @where + ') as p where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

--print @sqlstr
insert into log(content) values(@sqlstr)
--select *from log order by addtime desc 
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by goodsid desc) as rowno from product(nolock) p left join goods(nolock) g on p.productid=g.productid
where ' + @where + ') as p)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_LimitTime_RuleAndPdt_Get]    脚本日期: 04/09/2012 18:27:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-12-16>
-- Description:	<获取限时抢购活动及商品>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_LimitTime_RuleAndPdt_Get]
@errorFlag int output,
@errorMsg varchar(200) output
AS
BEGIN
--获取当天和预告的限时抢购活动
--select ruleid,rulename,begintime,endtime 
--into #r
--from pmtrule(nolock)
--where basictype='goods' and subtype='limittime' and endtime>getdate() or datediff(d,getdate(),endtime)=0 
--order by ruleid
select p.* 
into #r
from 
(
select ruleid,rulename,begintime,endtime 
from pmtrule(nolock)
where basictype='goods' and subtype='limittime' and endtime>getdate()
union
select ruleid,rulename,begintime,endtime 
from pmtrule(nolock)
where basictype='goods' and subtype='limittime' and datediff(d,getdate(),endtime)=0
) as p
order by p.ruleid

--返回活动
select * from #r

--查询活动对应的商品
select r.ruleid,g.productid,g.goodsid,p.productname,g.pmtnumber,g.balance,p.shortdesc,p.marketprice,p.memberprice,g.pmtprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5
from #r r,pmtgoods g(nolock),product p(nolock)
where r.ruleid=g.ruleid and g.productid=p.productid  order by g.sort asc

END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Login_Record]    脚本日期: 04/09/2012 18:27:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-07-07>
-- Description:	<记录登录信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Login_Record] 
	@MemberID int = NULL,--会员ID
	@Account varchar(50) = NULL,
	@Password varchar(50) = NULL,--密码
	@ReturnResult varchar(50) = NULL,
	@HTTP_REFERER varchar(200) = NULL,
	@AbsoluteUri varchar(200) = NULL,
	@IP varchar(50) = NULL,
	@SessionID varchar(50) = NULL,
	@LoginType tinyint = NULL
AS

INSERT loginrecord(MemberID, Account, Password, ReturnResult, HTTP_REFERER, AbsoluteUri, IP, SessionID, LoginType)
VALUES (@MemberID, @Account, @Password, @ReturnResult, @HTTP_REFERER, @AbsoluteUri, @IP, @SessionID, @LoginType)

RETURN SCOPE_IDENTITY()

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_MainStatisics_Get]    脚本日期: 04/09/2012 18:27:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-08-20>
-- Description:	<后台Main页面的一些统计数据>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_MainStatisics_Get] (
@message varchar(1000) output
)
AS
Begin
declare @temp varchar(10)
--未处理商品咨询
select @temp= Count(*)from productask where status=0
select @message=@temp+','
--未处理商品评价
select @temp=Count(*)from ProductReview(nolock) where status=0 and reviewtype=1
select @message=@message+@temp+','
--未处理客户投诉
select  @temp=count(*)from complaint(nolock) where status=0 and AdminDelete = 0
select @message=@message+@temp+','
--未处理客户留言
select @temp= Count(*)from review(nolock)where reply='' 
select @message=@message+@temp+','
--未处理商品返修
select  @temp=Count(*)from Repair(nolock) where isConfirm=0
select @message=@message+@temp+','
--未处理订单留言
SELECT  @temp=Count(*) FROM OrderReview(nolock) where Reply = ''
select @message=@message+@temp+','
----未处理订单
--SELECT  @temp=COUNT(*) FROM Orders(nolock) where Status <= 2  and isdel=0
--select @message=@message+@temp+','
--等待发货的订单
SELECT  @temp=COUNT(*) FROM Orders(nolock) where ((paytype<5 and Status between 2 and 5 )or(paytype>=5 and status between 3 and 5)) and isdel=0
select @message=@message+@temp+','
----所有销售统计
--select isnull(sum(Amount),0)from financedetail(nolock) where supplierid=0 and status>-1
----今年销售统计
--select isnull(sum(Amount),0)from financedetail(nolock) where supplierid=0 and datediff(year,ordertime,getdate())=0 and status>-1
--今月销售统计
select @temp=isnull(sum(Amount),0)from financedetail(nolock) where supplierid=0 and datediff(month,ordertime,getdate())=0 and status>-1
select @message=@message+@temp+','
--今日销售统计
select @temp=isnull(sum(Amount),0)from financedetail(nolock) where supplierid=0 and datediff(day,ordertime,getdate())=0 and status>-1
select @message=@message+@temp+','
----注册会员统计
SELECT @temp=COUNT(*) FROM Member(nolock) WHERE Status <> -1 AND [Name] <> 'anonymous' and MemberID > 0
select @message=@message+@temp
End




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_MaxID_Get]    脚本日期: 04/09/2012 18:27:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- =============================================
-- Author:		<Hakkas>
-- Create date: <2010-04-21>
-- Description:	<获取表的最大ID>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_MaxID_Get] 
@tbname nvarchar(50),
@maxid int out
AS
begin
	select @maxid = MaxID from MaxIDs where TableName = @tbname
	update MaxIDs set MaxID = MaxID + 1 where  TableName = @tbname
end

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Member_Insert]    脚本日期: 04/09/2012 18:27:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-06-29>
-- Description:	<注册会员>
/*
引用该存储过程的存储过程：
1、XpProc_Order_Make
*/

-- 注册业务流程:
/*
1、如果关联会员卡的要先查询会员卡对应的会员组ID和赠送积分
2、添加会员资料；
2、赠送注册积分
*/
-- =============================================
CREATE PROC [dbo].[XpProc_Member_Insert]
	@Name nvarchar(100),--会员账号
	@Password nvarchar(100),--会员密码
	@Email nvarchar(50) = NULL,--电子邮箱
	@HideEmail tinyint = NULL,--是否接收本站邮件0：接收，1：不接收
	@GroupId int = NULL,--会员组ID
	@Remarks nvarchar(100) = NULL,--备注
	@AddDate datetime = NULL,--注册日期
	@QQ nvarchar(20) = NULL,--QQ
	@Phone nvarchar(20) = NULL,--电话
	@MSN nvarchar(100) = NULL,--MSN
	@Question nvarchar(255) = NULL,--找回密码的问题
	@Answer nvarchar(255) = NULL,--找回密码的答案
	@Sex int = NULL,--性别
	@Birthday datetime = NULL,--生日
	@Realname nvarchar(100) = NULL,--真实姓名
	@LastLog datetime = NULL,--最后一次登录时间
	@LogTimes int = NULL,--登录次数
	@Photo nvarchar(255) = NULL,--头像
	@Introduction nvarchar(255) = NULL,--自我介绍
	@AdvancePayment money = NULL,--预付款
	@Score int = NULL,--积分
	@Status int = NULL,--状态
	@Code nvarchar(50) = NULL,--上级代销员编号
	@Finance decimal(18, 2) = NULL,--代销提成金额
	@From int = NULL,--来源：0网上注册，1电话注册，2会员推荐，3其他推广方式
	@SupplierID int = NULL,--商家Id
	@IsToErp tinyint = NULL,--是否已同步到ERP
	@Expenditure decimal(18, 2) = NULL,
	@Mobile nvarchar(25) = NULL,--手机
	@AddressIDs nvarchar(25) = NULL,--所属地区ID
	@Address nvarchar(255) = NULL,--详细地址
	@PostCode nvarchar(50) = NULL,--邮编
	@Spending decimal(18, 2) = NULL,
	@CardNo varchar(20)=null,--会员卡卡号
	@CardPwd varchar(20)=null,--会员卡密码
	@RegScore int=null,--注册赠送积分
	@IP varchar(20)=null,--注册人IP
	@currentMemberID int=null ,--用于区分前台注册还是后台管理员添加会员。当前用户的会员ID，前台注册时传入-1
	@currentName Nvarchar(200)=null,--当前用户的会员ID，前台注册时传入null
	@memberid int output,--返回会员ID
	@errorFlag int output,--错误标识
	@errorMsg varchar(100) output--错误信息
AS
begin
set @errorflag=1
set @errorMsg=''

--判断会员名，电子邮件，手机号是否存在，已存在则不能注册
if exists (select memberid from member where name=@name and Status >= 0)
begin
select @errorflag=1
select @errorMsg='用户名已被使用，请重新选择'
return 
end

if(isnull(@name,'')='')
begin
select @errorflag=1
select @errorMsg='用户名不能为空'
return 
end

if(isnull(@email,'')<>'')
begin
if exists (select memberid from member where email=@email and Status >= 0)
begin
select @errorflag=1
select @errorMsg='电子邮件地址已被使用，请重新选择'
return 
end
end
--else
--begin
--	select @errorflag=1
--	select @errorMsg='电子邮件地址不能为空'
--	return 
--end

if(isnull(@mobile,'')<>'')
	begin
	if exists (select memberid from member where mobile=@mobile and Status >= 0)
	begin
	select @errorflag=1
	select @errorMsg='手机号码已被使用，请重新选择'
	return 
	end
end

--测试代销员是否存在
if isnull(@code,'admin')<>'admin'
begin
	if not exists(Select m.memberid From member m(nolock),agent a(nolock) Where m.memberid=a.memberid and  name=@code And m.status = 1 and a.status=1)
	begin
		select @errorflag=1
		select @errorMsg='指定的推广员不存在或被禁用，请重新选择'
		return 
	end
end

--会员卡的相关资料
declare @cardscore int,@addscore int,@agentMemberID int
--获取会员卡资料
if isnull(@CardNo,'')<>'' and isnull(@CardPwd,'')<>''
begin
	if exists(select *from Card(nolock) where status=1 and CardNo=@CardNo and PassWord=@CardPwd)
	begin
		select @GroupId=GroupID,@cardscore=Score,@agentMemberID=agentMemberID from Card(nolock) where status=1 and CardNo=@CardNo and PassWord=@CardPwd
		--代销员的名字
		select @Code=name from member(nolock) where memberid=@agentMemberID
	end
	else
	begin
		set @errorflag=1
		set @errormsg='会员卡卡号或密码不正确'
		return	
	end
end

begin try
begin tran
--计算积分
--select @addscore=isnull(@score,0)+isnull(@RegScore,0)+isnull(@cardscore,0)
--添加会员资料
INSERT member(
[Name], Password, Email, HideEmail, GroupId, Remarks, AddDate, --1
QQ, Phone, MSN, Question, Answer, Sex, Birthday, Realname, LastLog, --2
LogTimes, Photo, Introduction, AdvancePayment, Score, Status, --3
Code, Finance, [From], SupplierID, IsToErp, --4
Expenditure, Mobile, AddressIDs, Address, PostCode, Spending,RegIP --5
)
VALUES (
@Name, @Password, @Email, COALESCE(@HideEmail, (0)), COALESCE(@GroupId, (0)), @Remarks, COALESCE(@AddDate, getdate()), --1
@QQ, @Phone, @MSN, @Question, @Answer, COALESCE(@Sex, (-1)), @Birthday, @Realname, COALESCE(@LastLog, getdate()), --2
COALESCE(@LogTimes, (0)), @Photo, @Introduction, @AdvancePayment, 0, COALESCE(@Status, (1)), --3
@Code, COALESCE(@Finance, (0)), COALESCE(@From, (0)), COALESCE(@SupplierID, (0)), COALESCE(@IsToErp, (0)), --4
COALESCE(@Expenditure, (0)), COALESCE(@Mobile, ''), COALESCE(@AddressIDs, ''), COALESCE(@Address, ''), COALESCE(@PostCode, ''), COALESCE(@Spending, (0)),@IP --5
)
select @memberid=@@Identity

--添加注册赠送积分日志
if isnull(@RegScore,0)<>0
begin
exec XpProc_ScoreLog_Insert @memberid,@Mobile,@RegScore,1,1,0,null,'','','注册赠送积分','注册赠送积分',@IP,null,null,null,null
end


--激活会员卡
--更新会员卡的所属memberid
if isnull(@CardNo,'')<>'' and isnull(@CardPwd,'')<>''
begin
update Card set MemberID =@memberid ,ActiveDate = getDate(),status=0 where Status = 1  and CardNo = @CardNo and PassWord=@CardPwd
exec XpProc_ScoreLog_Insert @memberid,@Mobile,@cardscore,1,1,0,null,'','','激活会员卡获得积分','激活会员卡获得积分',@IP,null,null,null,null
end

--管理后台添加会员时
IF(@currentMemberID<>-1 and @currentName is not null)
begin
--要记录后台操作日志
INSERT INTO EventLog (MemberID,MemberName,RootCatID,SubCatID,Description,IP,AddTime) VALUES 
(@currentMemberID,@currentName,2,21,'添加用户:'+@name,@ip,getDate())
--添加积分日志
if(@score<>0)
	begin
	declare @flag int  
	if(@score>0)
	set @flag=1
	else
	set @flag=-1
	exec XpProc_ScoreLog_Insert @memberid,@Mobile,@score,@flag,1,0,null,'','','管理员修改积分','管理员修改积分',@IP,null,null,null,null
	end
end

--注册送优惠券
select c.couponid,c.number,isnull(c.Validity,30) as Validity,r.rulename
into #c
from pmtrule r(nolock),pmtcoupons c(nolock)
where r.basictype='register' and r.subtype='coupon' and getdate() between BeginTime and EndTime and r.ruleid=c.ruleid 

declare @couponid int,@SendReason varchar(100),@number int,@Validity int
declare coupon_items_cursor cursor for select * from #c

open coupon_items_cursor                                              
fetch next from coupon_items_cursor into @couponid,@number,@Validity,@SendReason
while @@fetch_status = 0
begin 
declare @begintime datetime,@endtime datetime
select @begintime=getdate(),@endtime=dateadd(dd,@Validity,getdate())
exec XpProc_Coupon_Issue @couponid,@memberid,@Name,@number,0,@SendReason,0,null,'system',@IP,4,@begintime,@endtime,@errorFlag,@errorMsg
fetch next from coupon_items_cursor into @couponid,@number,@Validity,@SendReason
end

close coupon_items_cursor                                              
deallocate coupon_items_cursor

select @errorFlag=0,@errorMsg='注册成功'
commit tran
end try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
end





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Member_Login]    脚本日期: 04/09/2012 18:27:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-07-07>
-- Description:	<会员登录>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Member_Login]
	@name nvarchar(100),--会员账号
	@password nvarchar(100),--会员密码
	@loginType tinyint,--登录方式
	@referer nvarchar(200),--登录前的访问网址
	@absoluteUri nvarchar(200),--登录网址
	@ip nvarchar(20),--登录的IP
	@sessionID nvarchar(30),--sessionid
	@memberID int out,--会员ID
	@status int out,--会员状态  
	@loginFlag int out, --是否登录成功
	@isMemberFlag int out,--是否存在该会员
	@errcount int out--登录失败次数
AS
begin
select @memberID=-1,@status=-1,@loginFlag=0,@isMemberFlag=0,@errcount=0
if exists(select memberid from member(nolock) where [name]=@name)
	begin
	print('存在该会员账号')
	select @isMemberFlag=1
	select @memberID=MemberID,@status=Status from Member(nolock) where [name]=@name and [Password] = @password AND Status >= 0
	if(@memberID>0)
		begin
		print('账号和密码验证通过')
		select @loginFlag=1
		--更新登录次数和最后一次登录的时间
		update Member set LastLog = getdate(),LogTimes = LogTimes + 1 where MemberID =@memberID
		--清除登录失败记录
		--delete from FailedLogins where ip=@ip
		end
	else
		begin
		print('账号和密码验证不通过')
		select @loginFlag=0
		/*
		select @errcount=errcount from FailedLogins where ip=@ip
		if(@errcount>0)
			begin
			update FailedLogins set errcount=errcount+1,lastupdate=getdate() where ip=@ip
			end
		else
			begin
			insert into FailedLogins (ip,errcount,lastupdate) values(@ip,1,getdate())
			end
		select @errcount=@errcount+1
		*/
		end
	end
else
	begin
	print('不存在该会员账号')
	select @loginFlag=0,@isMemberFlag=0
	/*		
	select @errcount=errcount from FailedLogins where ip=@ip
	if(@errcount>0)
		begin
		update FailedLogins set errcount=errcount+1,lastupdate=getdate() where ip=@ip
		end
	else
		begin
		insert into FailedLogins (ip,errcount,lastupdate) values(@ip,1,getdate())
		end
	select @errcount=@errcount+1
	*/
	end
print('记录登录日志')
insert into LoginRecord (MemberID,Account,[Password],ReturnResult,HTTP_REFERER,AbsoluteUri,IP,SessionID,LoginType)values(@memberID,@name,@password,@loginFlag,@referer,@absoluteUri,@ip,@sessionID,@loginType)
end



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Member_Update]    脚本日期: 04/09/2012 18:27:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2010-07-25>
-- Description:	<修改会员资料>

-- =============================================
CREATE PROC [dbo].[XpProc_Member_Update]
	@Name nvarchar(100),--会员账号
	@Password nvarchar(100),--会员密码
	@Email nvarchar(50) = NULL,--电子邮箱
	@HideEmail tinyint = NULL,--是否接收本站邮件0：接收，1：不接收
	@GroupId int = NULL,--会员组ID
	@Remarks nvarchar(100) = NULL,--备注
	@AddDate datetime = NULL,--注册日期
	@QQ nvarchar(20) = NULL,--QQ
	@Phone nvarchar(20) = NULL,--电话
	@MSN nvarchar(100) = NULL,--MSN
	@Question nvarchar(255) = NULL,--找回密码的问题
	@Answer nvarchar(255) = NULL,--找回密码的答案
	@Sex int = NULL,--性别
	@Birthday datetime = NULL,--生日
	@Realname nvarchar(100) = NULL,--真实姓名
	@LastLog datetime = NULL,--最后一次登录时间
	@LogTimes int = NULL,--登录次数
	@Photo nvarchar(255) = NULL,--头像
	@Introduction nvarchar(255) = NULL,--自我介绍
	@AdvancePayment money = NULL,--预付款
	@Score int = NULL,--积分
	@Status int = NULL,--状态
	@Code nvarchar(50) = NULL,--上级代销员编号
	@Finance decimal(18, 2) = NULL,--
	@From int = NULL,--来源方式
	@SupplierID int = NULL,--商家Id
	@IsToErp tinyint = NULL,--是否已同步到ERP
	@Expenditure decimal(18, 2) = NULL,
	@Mobile nvarchar(25) = NULL,--手机
	@AddressIDs nvarchar(25) = NULL,--所属地区ID
	@Address nvarchar(255) = NULL,--详细地址
	@PostCode nvarchar(50) = NULL,--邮编
	@Spending decimal(18, 2) = NULL,
	@RegScore int=null,--注册赠送积分
	@IP varchar(20)=null,--注册人IP
	@memberid int ,--会员ID

	@managerID int,--管理员ID
	@managerName varchar(50),--管理员名字
	@changedScore decimal(18,2),--修改会员资料时增加或减少的积分
	@flag int ,--标志位:-1扣减,0冻结,1增加积分，用于日志记录
	@modifyIp varchar(50),
	@errorFlag int output,--错误标识
	@errorMsg varchar(100) output--错误信息
AS
begin
set @errorflag=1
set @errorMsg=''

--判断会员名，电子邮件，手机号是否存在，已存在则不能注册
if exists (select memberid from member where name=@name and  Status >= 0  and memberid<>@memberid)
begin
select @errorflag=1
select @errorMsg='用户名已被使用，请重新选择'
return 
end

if(isnull(@name,'')='')
begin
select @errorflag=1
select @errorMsg='用户名不能为空'
return 
end

if exists (select memberid from member where email=@email and Status >= 0 and memberid<>@memberid)
begin
select @errorflag=1
select @errorMsg='电子邮件地址已被使用，请重新选择'
return 
end

if(isnull(@email,'')='')
begin
select @errorflag=1
select @errorMsg='电子邮件地址不能为空'
return 
end

if(isnull(@mobile,'')<>'')
	begin
	if exists (select memberid from member where mobile=@mobile and Status >= 0 and memberid<>@memberid)
	begin
	select @errorflag=1
	select @errorMsg='手机号码已被使用，请重新选择'
	return 
	end
end

--测试代销员是否存在
/*
if not exists(Select AgentID From Agent Where MemberName=@code And Status = 1)
begin
select @errorflag=1
select @errorMsg='指定的代销员不存在，请重新选择'
return 
end
*/

begin try
begin tran
update member 
set [Name]=@name, Password=@Password, Email=@Email, HideEmail=COALESCE(@HideEmail,(0)), GroupId=COALESCE(@GroupId,(0)), Remarks=@Remarks,
AddDate=COALESCE(@AddDate, getdate()), QQ=@QQ, Phone=@Phone, MSN=@MSN, Question=@Question, Answer=@Answer, Sex=COALESCE(@Sex, (-1)),
Birthday=@Birthday, Realname=@Realname, LastLog=COALESCE(@LastLog,getdate()), LogTimes=COALESCE(@LogTimes,(0)), Photo=@Photo, 
Introduction=@Introduction, AdvancePayment=@AdvancePayment, Score=COALESCE(@Score, (0)), Status= COALESCE(@Status, (1)),Code=@Code,
Finance=COALESCE(@Finance, (0)), [From]=COALESCE(@From, (0)), SupplierID=COALESCE(@SupplierID, (0)), IsToErp=COALESCE(@IsToErp, (0)),
Expenditure=COALESCE(@Expenditure, (0)), Mobile=COALESCE(@Mobile, ''), AddressIDs=COALESCE(@AddressIDs, ''), Address=COALESCE(@Address, ''),
PostCode=COALESCE(@PostCode, ''), Spending=COALESCE(@Spending, (0)),RegIP=@IP where memberid=@memberid --5

--添加积分日志,管理员修改积分
if isnull(@changedScore,0)<>0
begin
exec XpProc_ScoreLog_Insert @memberid,@Mobile,@changedScore,@flag,1,0,null,'','','管理员修改积分','管理员修改积分',@modifyIp,null,null,@managerID,@managerName
end

select @errorflag=0
select @errorMsg='成功修改会员资料'
commit tran
end try

begin catch
rollback
set @errorflag=1
set @errorMsg='数据库操作发生错误了'
end catch
end





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_MemberAddressInfo_Update]    脚本日期: 04/09/2012 18:27:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Hakkas@qq.com>
-- Create date: <2011-10-26>
-- Description:	<通过地址簿更新会员的手机号和地址信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_MemberAddressInfo_Update]

AS
BEGIN
select * into #r from
(
select m.memberid,m.name,m.realname,m.phone,m.mobile,m.address,m.addressids,r.ReceiverPhone,r.ReceiverMobile,r.ReceiverName,r.ReceiverAddress,r.AddressID,row_number() over
(
partition by m.memberid
order by r.ReceiverAddressID
)
as rowno
from member m
left join receiveraddress r 
on m.memberid=r.memberid
)a
where rowno=1

delete from #r where addressid is null or addressids is not null
--select * from #r
update m set m.realname=r.receivername,m.mobile=r.receivermobile,m.address=r.receiveraddress,m.addressids=r.addressid from member m,#r r where m.memberid=r.memberid

drop table #r

END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_MemberBookTG_Delete]    脚本日期: 04/09/2012 18:27:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-10>
-- Description:	<批量删除MemberBookTG中的团购购买申请>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_MemberBookTG_Delete]
@uids varchar(8000)=null,
@errorflag int=null output,
@errormsg varchar(200)=null output
AS
BEGIN
set nocount on
declare @deltotal int --将要删除的数量
declare @deltotaled int --已经删除的数量
select * into #t from SplitToTable_Func(@uids,',')
select @deltotal=count(*)from #t
delete  MemberBookTG from  MemberBookTG mb(nolock),#t t where mb.uid=t.Value
select @deltotaled=@@rowcount
if @deltotal=@deltotaled
begin
select @errorFlag=0
select @errorMsg='删除成功'
end
else if (0<@deltotaled and @deltotaled<@deltotal)
begin
select @errorFlag=1
select @errorMsg='部分删除'
end
else
begin
select @errorFlag=1
select @errorMsg='删除失败'
end
end


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_MemberBookTG_Get]    脚本日期: 04/09/2012 18:27:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-10>
-- Description:	<获取参于购买团购商品会员提交的相关信息，一条记录代表会员下了一个订单>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_MemberBookTG_Get]
@ruleid int=null,
@gid int ,
@status int=-1,
@pageSize int =16,--每页显示
@pageNo int=1,--页码
@totalpage int=null output,--总页数
@totalcount int=null output,--总记录数
@errorflag int=null output,
@errormsg varchar(200)=null output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = '1=1'

--@gid=0,表示查找所有团购商品的购买记录，>0代表查找某个团购商品的购买记录
if isnull(@gid,0)<>0
select @where=@where+' and goodsid='+convert(varchar(20),@gid)

--@status -1代表查找不限制是否已生成订单，0代表还未生成订单，1代表已生成订单
if isnull(@status,-1)<>-1 
select @where=@where+' and status='+convert(varchar(1),@status)
select @sqlstr='select * from (
select UID,RuleID,RuleName,RuleNo,MemberID,ProductID,GoodsID,ProductName,Quantity,PmtPrice,Status,ReceiverAddress,ReceiverPostalCode,ReceiverName,ReceiverPhone,ReceiverMobile,Row_number() over(order by addtime desc) as rowno
from memberbooktg (nolock) where '+@where+')as temp 
where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
--获取分页商品datatable[1]
--insert log(content)values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by addtime desc) as rowno from pmtrule pr(nolock),pmtgoods pg(nolock),product p(nolock),goods g(nolock) where '+@where+')as temp)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output
select @totalcount=isnull(@totalcount,0)
select @totalpage=ceiling(@totalcount*1.0 / @pagesize)
end










GO
/****** 对象:  StoredProcedure [dbo].[XpProc_MemberDetails_Get]    脚本日期: 04/09/2012 18:27:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-10-20>
-- Description:	<获取会员的详细信息，充实MemberDetails实体类>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_MemberDetails_Get] 
@memberid int
AS
BEGIN
SELECT 
MemberID,[Name],[Password],Email,HideEmail,GroupId,g.GroupName,convert(decimal(18,2),g.Discount/10) as discount,Remarks,AddDate,QQ,Phone,MSN,Question,Answer,Sex,
Birthday,Realname,LastLog,LogTimes,Photo,Introduction,AdvancePayment,Score,Status,Code,Finance,[From],
SupplierID,Expenditure,Mobile,AddressIDs,Address,PostCode,Spending,Logo
FROM Member m(nolock),MemberGroup g(nolock)
WHERE m.MemberID=@memberid and m.GroupID=g.MemberGroupID
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_MemberInfo_Get]    脚本日期: 04/09/2012 18:27:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-08-16>
-- Description:	<根据手机号，电话号或用户名来查找会员资料>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_MemberInfo_Get] (
@query varchar(400)  , --查找的内容
@type varchar(10)=null,--标识按手机号，电话号还是用户名来查找会员
@errorFlag int=0 output
)
AS
Begin
select @errorFlag=0
select MemberID,Name,GroupId,GroupName,Discount,AdvancePayment,Score from member(nolock),MemberGroup(nolock) where (mobile=@query or phone=@query or name=@query) and Member.GroupId=MemberGroup.MemberGroupId
--if(@type='mobile')
--begin
--select MemberID,Name,GroupId,GroupName,Discount,AdvancePayment,Score from member(nolock),MemberGroup(nolock) where name=@query and Member.GroupId=MemberGroup.MemberGroupId
--select @errorFlag=0
--end
--else if(@type='phone')
--begin
--select MemberID,Name,GroupId,GroupName,Discount,AdvancePayment,Score from member(nolock),MemberGroup(nolock) where name=@query and Member.GroupId=MemberGroup.MemberGroupId
--select @errorFlag=0
--end
--else if(@type='name')
--begin 
--select MemberID,Name,GroupId,GroupName,Discount,AdvancePayment,Score from member(nolock),MemberGroup(nolock) where name=@query and Member.GroupId=MemberGroup.MemberGroupId
--select @errorFlag=0
--end
end



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_MemberPassword_Update]    脚本日期: 04/09/2012 18:27:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-12-08>
-- Description:	<后台管理员修改会员密码>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_MemberPassword_Update] 
@adminid int,
@adminpassword varchar(36),
@memberName varchar(200),
@memberpassword varchar(36),
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
if not exists(select memberid from member(nolock) where name=@memberName)
begin
select @errorflag=1,@errormsg='会员不存在'
return
end
select @errorflag=1,@errormsg='操作未完成'
if not exists(select adminid from admin(nolock) where adminid=@adminid and password=@adminpassword)
begin
select @errorflag=1,@errormsg='管理员密码错误'
return
end
Begin Try
update member set password=@memberpassword where name=@membername
if @@error=0
select @errorflag=0,@errormsg='成功修改会员密码'
else
select @errorflag=1,@errormsg='操作未完成'
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_MemberScore_Update]    脚本日期: 04/09/2012 18:27:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2010-12-21>
-- Description:	<后台修改会员积分,用于会员积分清零>

-- =============================================
CREATE PROC [dbo].[XpProc_MemberScore_Update]
@memberids varchar(8000),--会员IDs
@changedScores varchar(8000) ,--更改的积分s
@adminid int,--管理员ID
@realname varchar(50) =null,--管理员真实姓名
@flag int ,--标志位:-1扣减,0冻结,1增加积分，用于日志记录
@modifyIp varchar(50),
@errorFlag int output,--错误标识
@errorMsg varchar(100) output--错误信息
AS
begin
set @errorflag=1
set @errorMsg=''
declare @description varchar(200)
begin try
create table #t(id int,memberid int,score int)
if @changedScores is null or @changedScores=''
--积分清零可以不用传要修改的积分参数过来，当然传过来也没有问题
begin
if @memberids is null or @memberids=''--清空所有的会员的积分
insert into #t select 1,memberid,score from member
else
insert into #t select id,value as memberid,score from SplitToTable_Func(@memberids,','),member where member.memberid=value
select @description='管理员清空积分'
end
else
begin
insert into #t select a.id,memberid,score from 
(select id,value as memberid from dbo.SplitToTable_Func(@memberids,','))a,
(select id,value as score from dbo.SplitToTable_Func(@changedScores,','))b
where a.id=b.id
select @description='管理员修改积分'
end
--添加积分日志,管理员修改积分
--遍历游标
begin tran
declare @memberid int,@score int--要更新会员ID，会员积分
declare memberid_items_cursor cursor for select memberid,score from #t 
open memberid_items_cursor                                                    
fetch next from memberid_items_cursor into @memberid,@score
while @@fetch_status = 0                        
begin 
if @score<>0
exec XpProc_ScoreLog_Insert @memberid,'',@score,@flag,1,0,null,'','',@description,@description,@modifyIp,null,null,@adminid,@realname
fetch next from memberid_items_cursor into @memberid,@score
end
--遍历结束
close memberid_items_cursor                                                    
deallocate memberid_items_cursor

select @errorflag=0
select @errorMsg='成功更新会员积分'
commit tran
end try
begin catch
rollback
set @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
end catch
end
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_MemberThirdPart_Insert]    脚本日期: 04/09/2012 18:27:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-06-29>
-- Description:	<用于第三方系统登录时注册第三方系统的会员>
-- 第三方系统标识:
/*
tx:腾讯
rr:人人网
kx:开心网
tb:支付宝
sina:新浪微博
139:139邮箱
db:豆瓣网
*/
-- =============================================
CREATE PROC [dbo].[XpProc_MemberThirdPart_Insert]
	@uid nvarchar(100),--第三方系统返回的ID
	@Password nvarchar(50),--会员密码
	@Email nvarchar(50) = NULL,--电子邮箱
	@Sex int = 0,--性别
	@Birthday datetime = NULL,--生日
	@NickName varchar(50)=null,--昵称
	@Remark nvarchar(100) = NULL,--备注
	@IP varchar(20)=null,--注册人IP
	@tpno varchar(20),--第三方系统的标志
	@code varchar(50),--代销员账号
	@memberid int output,--返回会员ID
	@errorFlag int output,--错误标识
	@errorMsg varchar(100) output--错误信息
AS
begin
begin try
declare @name varchar(50),@tpflag varchar(10),@random varchar(5)
select @memberid=-1
--判断是否存在该系统对应的会员
if @tpno='tx'
begin
update member set tpid=@uid where tpno='tx' and tpid=@nickname and adddate<'2012-03-31'
end

select @memberid=memberid from member where tpno=@tpno and tpid=@uid and Status >= 0

if @memberid=-1
begin
--不存在对应会员，要插入会员
--生成五位数的随机数
exec XpProc_Common_Random_Cet 2,@random out

--构造用户名
select @name=case when @tpno='tx' then @tpno+@NickName+@random else @tpno+@uid+@random end

--判断会员名是否存在，已存在则不能注册
if exists (select memberid from member where name=@name and Status >= 0)
begin
select @errorflag=1
select @errorMsg='用户名已被使用，请重新选择'
return 
end

if(isnull(@email,'')<>'')
begin
if exists (select memberid from member where email=@email and Status >= 0)
begin
select @errorflag=1
select @errorMsg='电子邮件地址已被使用，请重新选择'
return 
end
end

--添加会员资料
INSERT member(
[Name], Password, Email,Sex, Birthday,LogTimes,Remarks,RegIP,TPNo,TPID,NickName,code
)
VALUES (
@Name, @Password, @Email,COALESCE(@Sex, (0)), @Birthday,1,@Remark,@IP,@tpno,@uid,@NickName,@code
)
select @memberid=@@Identity
select @errorFlag=0,@errorMsg='注册成功'
end


else
begin
--存在会员，直接返回会员ID
--更新登录次数和最后一次登录的时间
update Member set LastLog = getdate(),LogTimes = LogTimes + 1 where MemberID =@memberID
select @errorFlag=0,@errorMsg='匹配到会员'
end
end try

Begin Catch
-- 捕捉错误
select @memberid=-1,@errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
end















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_MyOrders_Get]    脚本日期: 04/09/2012 18:27:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-09-05>
-- Description:	<订单中心,会员得到分页的订单数据据>
-- Debug:
/*
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_MyOrders_Get]
@memberid int, --会员ID
@key varchar(100)=null,--关键字
@status int=-1,--查询的订单状态
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@totalpage int output,--总页数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
--declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0
Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)

if isnull(@memberID,-1)<>-1
select @where=' memberID='+cast(@memberID as varchar(10))
else
select @where=''

if isnull(@status,-1)<>-1
begin
select @where= CASE @status
WHEN '0' THEN @where+' and status <=2' --未付款
WHEN '1' THEN (@where+' and status between 2 and 9')--未完成
WHEN '2' THEN (@where+' and status =12')--已完成
WHEN '3' THEN (@where+' and status =10')--已取消
WHEN '4' THEN (@where+' and status = 11')--已失败
END
end

if isnull(@key,'')<>''
select @where=@where+' and OrderNo like ''%' + @key + '%'''

select @sqlstr='select rowno,OrderID,OrderNo,OrderTime,TotalPrice,NeedPayMoney,ProductPrice,AdvancePayment,ScoreAmount,PayType,PaymentType,status from(
select OrderID,OrderNo,OrderTime,TotalPrice,NeedPayMoney,ProductPrice,AdvancePayment,ScoreAmount,PayType,PaymentType,status,Row_number() over(order by orderid desc) as rowno 
from Orders(nolock)
where ' + @where + ') as o where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
Execute(@sqlstr)

--获取总记录数和总页数
declare @totalcount int 
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by orderid desc) as rowno from orders(nolock) where ' + @where + ') as p)'
--print @sqlstr

Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)
--select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_NewPdtAsk_Select]    脚本日期: 04/09/2012 18:27:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-04-29>
-- Description:	<用于商家店铺页，获商家的商品的最新问答及商品总的问答的数量>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_NewPdtAsk_Select]
@sid int --商家ID
AS
BEGIN

--连接productAsk,Product表，得到商品的名称，价格等信息并插入临时表中
SELECT * into #temp from (select pa.replytime,pa.supplierid, pa.productaskid,pa.productid,productname,marketprice,memberprice,membername,categoryno,thumbnailimg,(MarketPrice-MemberPrice)as [save],cast(round((memberprice/marketprice)*10,1) as decimal(3,1)) as discount,body ,pa.addtime,reply,ImgFolder FROM productask pa(nolock) INNER JOIN product p(nolock) ON pa.productid=p.productid  WHERE pa.supplierid=@sid AND ishide=0)as a
--得到商家的商品最新的回复及总的回复数量
select a.*,b.askcount from(select * from #Temp as t where productaskid in(select max(productaskid) from #temp where t.productid=productid))as a
inner join (SELECT productid,COUNT(productid)as askcount from productask(nolock) where supplierid=@sid and ishide=0 GROUP BY productid) as b on a.productid=b.productid
END

--exec XpProc_NewPdtAsk_Select 10001






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_NotReviewProduct_Select]    脚本日期: 04/09/2012 18:27:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-18>
-- Description:	<得到某个会员待评价的商品,在ProductReview中调用>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_NotReviewProduct_Select] (
@memberid int --会员ID
)
AS
begin
--得到某个会员待评价的商品
--select Product.ProductID,Product.ProductName,Product.ProductNo,Orders.OrderID,Orders.OrderNo,Orders.OrderTime,OrderProduct.OrderID,OrderProduct.ProductID 
--from Product(nolock),Orders(nolock),OrderProduct(nolock)
--where Product.ProductID = OrderProduct.ProductID and Orders.OrderID = OrderProduct.OrderID and Orders.Status in(7,12) and
--Orders.MemberID =  @memberid
--and Product.ProductID not in(select ProductID from ProductReview(nolock) where ProductReview.OrderID=Orders.OrderID) order by ordertime desc

select orderid,orderproductid,orderno,productid,ProductNo,productname,OrderTime
from OrderProduct p(nolock)
where p.CommentStatus=1 and p.MemberID = @memberid 
end
--exec XpProc_NotReviewProduct_Select 18
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ObjectModifyTime_View]    脚本日期: 04/09/2012 18:27:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-1-1>
-- Description:	<查看数据库对象的更新时间>
/*
对象类型：
AF = 聚合函数 (CLR)
C = CHECK 约束
D = DEFAULT（约束或独立）
F = FOREIGN KEY 约束
PK = PRIMARY KEY 约束
P = SQL 存储过程
PC = 程序集 (CLR) 存储过程
FN = SQL 标量函数
FS = 程序集 (CLR) 标量函数
FT = 程序集 (CLR) 表值函数
R = 规则（旧式，独立）
RF = 复制筛选过程
S = 系统基表
SN = 同义词
SQ = 服务队列
TA = 程序集 (CLR) DML 触发器
TR = SQL DML 触发器
IF = SQL 内联表值函数
TF = SQL 表值函数
U = 表（用户定义类型）
UQ = UNIQUE 约束
V = 视图
X = 扩展存储过程
IT = 内部表
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ObjectModifyTime_View]
AS
BEGIN
/*
select type,[name],modify_date 
from sys.objects 
where 
type = 'P' --存储过程
or type='U' --用户表
or type='v' --视图
or type='pk' --主键约束
or type='F' --外键约束
or type='C' --CHECK 约束
--or type='D' --DEFAULT（约束或独立）
or type='IF' --SQL 内联表值函数
or type='TF' --SQL 表值函数
or type='TR' --SQL DML 触发器
order by modify_date desc
*/
--存储过程
select '存储过程' as type,[name],modify_date,create_date from sys.objects where type = 'P' --存储过程
order by modify_date desc
--用户表
select '用户表' as type,[name],modify_date,create_date from sys.objects where type='U' --用户表
order by modify_date desc
--视图
select '视图' as type,[name],modify_date,create_date from sys.objects where type='v' --视图
order by modify_date desc
--主键约束
select '主键约束' as type,[name],modify_date,create_date from sys.objects where type='pk' --主键约束
order by modify_date desc
--外键约束
select '外键约束' as type,[name],modify_date,create_date from sys.objects where type='F' --外键约束
order by modify_date desc
--check约束
--select 'check约束' as type,[name],modify_date from sys.objects where type='C' --CHECK 约束
--order by modify_date desc
--函数
select '函数' as type,[name],modify_date,create_date from sys.objects where type='IF' --SQL 内联表值函数
or type='TF' --SQL 表值函数
order by modify_date desc
--触发器
select '触发器' as type,[name],modify_date,create_date from sys.objects where type='TR' --SQL DML 触发器
order by modify_date desc
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Order_Cancel]    脚本日期: 04/09/2012 18:27:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<liwenhai>
-- Create date: <2012-01-10>
-- Description:	<取消订单的操作>
--取消已付款的订单就要退款，取消未付款或货到付款的订单就不用退款。并且取消订单还涉及到商品库存的更新，
--因为现在是顾客下单就更新商品的库存。退款还涉及到优惠券和商品价格，运费的计算。
--先款的订单付款后就向财务明细表中插入相应的纪录，所以当已付款的订单取消是，要把明细表中的Status状态置为-1.
--先货的订单确认后也会向财务明细表中插入相应的纪录。当订单被取消时明细表的Status也置为-1
--1、顾客或商家可以手动取消，顾客在一定时间内未付款的订单。（订单状态，status=10,订单已取消）
--2、商家可以手动取消，已付款但未发货的订单（订单状态，status=8, 等待退款）
--3、商家可以手动取消，先货的已确认但未发货的订单（订单状态，status=10,订单已取消）
--4、商家可以手动取消，先款的已发货的订单（订单状态，status=8, 等待退款）
--5、商家可以手动取消，先货的已发货的订单（订单状态，status=10,订单已取消）
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Order_Cancel]
@orderID int =null,--订单ID
@orderNo varchar(50)=null,--订单编号
@operator int =null,--操作人ID
@opname varchar(20)=null,--操作人姓名
@OPRule varchar(50)=null,--操作角色 顾客，系统，商家,管理员
@OPDesc varchar(200)=null,--操作描述
@flag bit=null,--取消类型，1是商家取消订单，0是顾客自已取消订单
@remark varchar(200)=null,--操作备注
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
begin try

--以下三个参数用于保存订单里的商品ID，货品ID跟购买数量，传给XpProc_ProductStorage_Update以更新商品的数量及skumap
declare @productids varchar(8000),@goodsids varchar(8000),@quantitys varchar(8000)
select @productids='',@goodsids='',@quantitys=''
--得到这个订单的状态，订单编号或订单ID，订单类型，订单所属会员
declare @paytype int,@prestatus int,@operatorid int
if @OrderNo is NULL
begin
select @PreStatus=status ,@orderno=orderno ,@paytype=paytype,@operatorid=memberid
from orders(nolock)
where orderid=@OrderID
end
else
begin
select @PreStatus=status ,@OrderID=orderid ,@paytype=paytype,@operatorid=memberid 
from orders(nolock)
where orderno=@OrderNo
end
declare @memberid int --会员ID
select @memberid=m.memberid,@orderno=orderno
from orders o(nolock),member m(nolock) 
where o.orderid=@orderid and m.memberid=o.memberid

--1.1 更改待返券的状态为已取消
--1.2 更新商品的库存跟skumap
--1.3 订单操作日志
--1.4 更新订单的状态
--1.5 更新财务明细表的Status=-1 (订单已付款或已确认的情况下)
--1.6 更新agentFinance表中的status状态为-1，表示这个提成无需结款(订单已付款或已确认的情况下)
--1.7 更新商品的入库记录(订单已发货的情况下)
begin tran
	--返还使用的优惠券
	select distinct p.orderid,p.CouponsMemberID                                        
	into #usedcoupon                                        
	from orderproduct p(nolock)                                        
	where p.orderid=@orderid

	update m                                        
	set Status=1,UsedTimes=UsedTimes-1,IsUsed=0,UsedTime=null,UseUserID=null,m.OrderID=0,m.orderno=''                                      
	from CouponsMember m(nolock),#usedcoupon c(nolock)                                        
	where c.CouponsMemberID=m.UID 

	--更改待返券的状态为已取消
	update ordercoupon set status=-1 where orderid=@orderid
	--更新商品的库存跟skumap,这个是无论订单在什么状态下都要执行的
	--更新商品的库存量,跟盘点库存共用一个存储过程
	--exec XpProc_ProductStorage_Update @orderid,1
	select @productids=@productids+','+cast(productid as varchar),
	@goodsids=@goodsids+','+cast(goodsid as varchar),@quantitys=@quantitys+','+cast(quantity as varchar)
	from orderproduct (nolock) where orderid=@orderid
	select @productids=stuff(@productids,1,1,''), @goodsids=stuff(@goodsids,1,1,''), @quantitys=stuff(@quantitys,1,1,'')
	exec XpProc_ProductStorage_Update @productids,@goodsids,@quantitys,1
--取消先款的订单
if @paytype<5
begin
	if(@flag=0)
	begin
		if(@operatorid=@memberid)--顾客自已的订单才可以取消
		begin
			if(@prestatus=0)--只有没有付款的订单才可以取消
			begin
				if(@remark is null or @remark='')
				select @remark='会员主动取消订单'
				---订单操作日志
				exec XpProc_OrderOpLog_Add @orderid,@orderno,@opname,@operator,@OPRule,@remark,@remark,10,1
				--更新订单的状态
				update orders set status=10,canceltype='会员主动取消订单',canceltime=getdate() where orderid=@orderid 
				set @errorFlag=0
				set @errorMsg='订单已取消'
			end
			else
			begin
				set @errorFlag=0
				set @errorMsg='会员不能取消已付款的订单'
			end
		end
		else
		begin
			set @errorFlag=0
			set @errorMsg='会员只能取消自已的订单'
		end
	end
	--1、@prestatus=0取消在一定时间内未付款的订单。（订单状态，status=10,订单已取消）
	--2、@prestatus=2取消已付款但未发货的订单（订单状态，status=8, 等待退款）
	--3、@prestatus=6取消先款的已发货的订单（订单状态，status=8, 等待退款）
	else if(@flag=1)--商家缺货时取消订单
	begin
		if(@prestatus=0)
		begin
			if(@remark is null or @remark='')
			select @remark='商家取消未付款的订单'
			exec XpProc_OrderOpLog_Add @orderid,@orderno,@OPName,@operator,@OPRule,@remark,@remark,10,1
			--更新订单的状态
			update orders set status=10,canceltype='商家取消订单',canceltime=getdate() where orderid=@orderid 
			set @errorFlag=0
			set @errorMsg='订单已取消'
		end
		else if(@prestatus=2)--已付款，取消订单后要返还货款
		begin
			if(@remark is null)
			select @remark='商家未能发货取消订单'
			--操作日志
			exec XpProc_OrderOpLog_Add @orderid,@orderno,@opname,@operator,@OPRule,@remark,@remark,8,1
			--更新订单的状态
			update orders set status=8,canceltype='商家取消订单',canceltime=getdate() where orderid=@orderid
			--更新财务明细表的Status=-1
			update FinanceDetail set status=-1 where orderno=@orderno
			--更新agentFinance表中的status状态为-1，表示这个提成无需结款
			exec XpProc_AgentFinance_Status_Update @orderid
			set @errorFlag=0
			set @errorMsg='订单已取消,等待运营商退款'
		end
		else if(@prestatus=6)
		begin
			if(@remark is null or @remark='')
			select @remark='商家取消已发货的订单'
			--操作日志
			exec XpProc_OrderOpLog_Add @orderid,@orderno,@opname,@operator,@OPRule,@remark,@remark,8,1
			--更新订单的状态
			update orders set status=8,canceltype='商家取消订单',canceltime=getdate() where orderid=@orderid
			--更新财务明细表的Status=-1
			update FinanceDetail set status=-1 where orderno=@orderno
			--更新agentFinance表中的status状态为-1，表示这个提成无需结款
			exec XpProc_AgentFinance_Status_Update @orderid
			--更新商品的入库记录
			------------
			set @errorFlag=0
			set @errorMsg='订单已取消,等待运营商退款'
		end
		else
		begin
			set @errorFlag=1
			set @errorMsg='当前的订单不能取消'
		end
	end
end
--先货后款的订单
else 
begin
	if(@flag=0)--顾客主动取消订单
	begin
		if(@operatorid=@memberid)--顾客自已的订单才可以取消
		begin
			if(@prestatus=0 or @prestatus=1 or @prestatus=2 )--只有未确认的订单才可以取消
			begin
				if(@remark is null or @remark='')
				select @remark='会员主动取消订单'
				--操作日志
				exec XpProc_OrderOpLog_Add @orderid,@orderno,@opname,@operator,@OPRule,@remark,@remark,10,1
				--更新订单的状态
				update orders set status=10,canceltype='会员主动取消订单',canceltime=getdate() where orderid=@orderid 
				set @errorFlag=0
				set @errorMsg='订单已取消'
			end
			else
			begin
				set @errorFlag=0
				set @errorMsg='已确认的订单不能取消'
			end
		end
		else
		begin
			set @errorFlag=0
			set @errorMsg='会员只能取消自已的订单'
		end
	end
	--1、@prestatus=0取消在一定时间内确认的订单。（订单状态，status=10,订单已取消）
	--2、@prestatus=2取消先货的已确认但未发货的订单（订单状态，status=10,订单已取消）
	--3、@prestatus=6取消先货的已发货的订单（订单状态，status=10,订单已取消）
	else if(@flag=1)--商家取消的订单
	begin
		if(@prestatus=0 or @prestatus=1 or @prestatus=2 )--只有未确认的订单
		begin
			if(@remark is null or @remark='')
			select @remark='商家取消未确认的订单'
			--操作日志
			exec XpProc_OrderOpLog_Add @orderid,@orderno,@opname,@operator,@OPRule,@remark,@remark,10,1
			update orders set status=10,canceltype='商家取消订单',canceltime=getdate() where orderid=@orderid 
			set @errorFlag=0
			set @errorMsg='订单已取消'
		end
		else if(@prestatus=3)--商家已确认订单
		begin
			if(@remark is null or @remark='')
			select @remark='商家取消已确认的订单'
			---订单操作日志
			exec XpProc_OrderOpLog_Add @orderid,@orderno,@opname,@operator,@OPRule,@remark,@remark,10,1
			--更新订单的状态
			update orders set status=10,canceltype='商家取消订单',canceltime=getdate() where orderid=@orderid
			--更新财务明细表的Status=-1
			update FinanceDetail set status=-1 where orderno=@orderno
			--更新agentFinance表中的status状态为-1，表示这个提成无需结款
			exec XpProc_AgentFinance_Status_Update @orderid
			set @errorFlag=0
			set @errorMsg='订单已取消'
		end
		else if(@prestatus=6)
		begin
			if(@remark is null or @remark='')
			select @remark='商家取消已发货的订单'
			--操作日志
			exec XpProc_OrderOpLog_Add @orderid,@orderno,@opname,@operator,@OPRule,@remark,@remark,8,1
			--更新订单的状态
			update orders set status=10,canceltype='商家取消订单',canceltime=getdate() where orderid=@orderid
			--更新财务明细表的Status=-1
			update FinanceDetail set status=-1 where orderno=@orderno
			--更新agentFinance表中的status状态为-1，表示这个提成无需结款
			exec XpProc_AgentFinance_Status_Update @orderid
			--更新商品的入库记录
			------------
			set @errorFlag=0
			set @errorMsg='订单已取消'
		end
	end
end
commit tran
end try

begin catch
	-- 捕捉错误
	rollback tran
	select @errorflag=1
	select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
	print @errormsg
	Return
end catch
END






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Order_Complete]    脚本日期: 04/09/2012 18:27:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-11-24>
-- Description:	<完成订单操作>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Order_Complete]
@orderID int =null,--订单ID
--@orderNo varchar(50)=null,--订单编号
@operator int =null,--操作人ID
@opname varchar(20)=null,--操作人姓名
@OPRule varchar(50)=null,--操作角色 顾客，系统，商家,管理员
@OPDesc varchar(200)=null,--操作描述
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
begin try
declare @memberid int, --会员ID
@membername varchar(20),--会员账号
@score int, --获得的订单积分			
@orderNo varchar(50),--订单编号
@memberemail nvarchar(200),--会员邮箱地址
@mobile varchar(20)--手机号

select @membername=m.[name],@mobile=m.mobile,@score=o.score,@memberid=m.memberid,@orderno=orderno,@memberemail=o.receiveremail 
from orders o(nolock),member m(nolock) 
where o.orderid=@orderid and m.memberid=o.memberid

begin tran
--向订单操作日志表中插入纪录
exec XpProc_OrderOpLog_Add @orderid,@orderNo,@opname,@operator,@OPRule,@OPDesc,@OPDesc,12,1
--更改订单状态为已完成
update orders set status=12,FinishTime=getdate() where orderid=@orderid

--1.1 更新商品的销量
update p set p.salenum=p.salenum+o.quantity
from product p(nolock),orderproduct o(nolock)
where p.productid=o.productid and o.orderid=@orderid

--1.2 更新会员的消费总金额	
UPDATE m SET Spending=Spending +productprice,Expenditure=Expenditure+productprice 
from orders o(nolock),member m(nolock)
where o.orderid=@orderid and m.memberid=o.memberid

--1.3 赠送
if(@score<>0)
begin
exec XpProc_ScoreLog_Insert @memberid,@mobile,@score,1,1,0,null,'交易积分',@orderid,'完成交易获得积分','完成交易获得积分',null,null,null,@operator,@opname
end

--1.4 会员更新消费总金额后可以获得的最高级别的会员组ID
declare @membergroupid int		
select top 1 @membergroupid= membergroupid from membergroup where leastamount<=(select expenditure from member where memberid=@memberid) order by leastamount desc
--如果更新了会员的会员组的话，还要发送邮件通知这个会员
if not exists(select top 1 memberid from member where memberid=@memberid and groupid=@membergroupid)
begin
	--更新会员所属的会员组
	UPDATE Member set GroupID =@membergroupid Where MemberID = @memberid
--				if not(@memberemail is null or @memberemail='')--会员的邮箱有效时，生成要发送的邮件的内容
--				begin
--					declare @content varchar(512)--邮件内容
--					select @content=replace(replace(replace(replace(cast(Centent as varchar(512)),'[name]',name),'[spend]',Expenditure),'[GroupName]',groupname),'[discount]',discount/10) 
--					from email ,(select name,Expenditure,groupname,discount from member,membergroup where member.groupid=membergroup.membergroupid and memberid=@memberid)a
--					where emailid=7
--					--发送邮件
--					------------------
--				end	
end

--1.5返券
declare @uid varchar(36),@couponid int,@number int,@Validity int,@supplierid int,@SendReason varchar(100),@ip varchar(50)
declare coupon_items_cursor cursor for select uid,couponid,subnumber,memberid,isnull(Validity,30) as Validity,supplierid,sendreason,ip from ordercoupon where orderid=@orderid and status=0
open coupon_items_cursor                                              
fetch next from coupon_items_cursor into @uid,@couponid,@number,@memberid,@Validity,@supplierid,@SendReason,@ip
while @@fetch_status = 0
begin 
declare @begintime datetime,@endtime datetime
select @begintime=getdate(),@endtime=dateadd(dd,@Validity,getdate())
exec XpProc_Coupon_Issue @couponid,@memberid,@membername,@number,@supplierid,@SendReason,0,null,'system',@ip,3,@begintime,@endtime,@errorFlag,@errorMsg
fetch next from coupon_items_cursor into @uid,@couponid,@number,@memberid,@Validity,@supplierid,@SendReason,@ip
end
close coupon_items_cursor                                              
deallocate coupon_items_cursor	
update ordercoupon set status=1 where orderid=@orderid

--1.6写购买记录
INSERT INTO BuyRecored
(OrderID,PdtID,PdtName,Quantity,MemberID,MemberName,BuyerName,Address,Phone,BuyTime,Type,Status)
select o.orderid,p.productid,isnull(p.productname,0),p.quantity,o.memberid,@membername,o.Receivername,
substring(receiveraddress,0,charindex(',',receiveraddress)+charindex(',',substring(receiveraddress,charindex(',',receiveraddress)+1,len(receiveraddress))))as Address
,ReceiverPhone,o.ordertime,1 as type,1 as status
from orders o(nolock),orderproduct p(nolock) 
where o.orderid=p.orderid and o.orderid=@orderid	

--订单完成后，更新agentFinance表中的status状态为1，表示未结款
exec XpProc_AgentFinance_Status_Update @orderid

select @errorFlag=0,@errormsg=''
commit tran
end try

begin catch
	-- 捕捉错误
	rollback tran
	select @errorflag=1
	select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
	print @errormsg
	Return
end catch
END





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Order_Confirm]    脚本日期: 04/09/2012 18:27:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-06-30>
-- Description:	<商家确认订单>
-- =============================================
create PROCEDURE [dbo].[XpProc_Order_Confirm]
	@orderID int =null,--订单ID
	@orderNo varchar(50)=null,--订单编号
	@OPName varchar(20) = NULL,--操作员的名称
	@operator int=Null,--操作员的会员ID
	@SupplierID int =null,--商家ID
	@OPRule varchar(50)=null,--操作角色 顾客，系统，商家,管理员
	@remark varchar(200)=null,--备注
	@errorFlag int=null output ,
	@errorMsg varchar(200)=null output
AS
BEGIN
	select @errorFlag=1
	select @errorMsg='订单未确认'
	declare @paytype int,@prestatus int,@operatorid int,@sid int,@ProductPrice decimal(18,2),@ordertime datetime,@totalPrice decimal(18,2)
	if @OrderNo is NULL
	begin
	select @PreStatus=status ,@orderno=orderno ,@paytype=paytype,@sid=supplierid,@ProductPrice=ProductPrice,@ordertime=ordertime,@totalPrice=totalPrice
	from orders(nolock)
	where orderid=@OrderID
	end
	else
	begin
	select @PreStatus=status ,@OrderID=orderid ,@paytype=paytype,@sid=supplierid,@ProductPrice=ProductPrice,@ordertime=ordertime,@totalPrice=totalPrice
	from orders(nolock)
	where orderno=@OrderNo
	end

	begin try
		begin tran
		if @paytype<>5 and @paytype<>6--非货到付款订单
		begin
			select @errorFlag =0			
			select @errorMsg='先款后货，不用确认'
		end
		else--货到付款
		begin
			if(@supplierid=@sid)--商家只能确认自已的订单
			begin
				if(@prestatus=0 or @prestatus=1 or @prestatus=2 )--订单还没有确认
				begin
					if(@remark is null)
					select @remark='商家已确认订单'
					exec XpProc_OrderOpLog_Add @orderid,null,@OPName,@operator,@OPRule,@remark,@remark,3,1
					update orders set status=3 where orderid=@orderid
					--插入财务明细表
					declare @yongjin money,@bprate float
					select @bprate=BPRate from supplier where supplierid=@supplierid
					select @yongjin = round(@ProductPrice*@bprate,2)
					exec XpProc_FinanceDetail_Insert @ordertime,@orderid,@orderno,@totalPrice,0,@yongjin,@supplierid,0

					--插入推广员的提成金额
					exec XpProc_AgentFinance_Add @orderid

					set @errorFlag=0
					set @errorMsg='订单已通过确认'
				end
			end
		end
		commit tran
	end try
	begin catch
		select @errorflag=1
		select @errorMsg=error_message()
		rollback tran
	end catch
END










GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Order_ConfirmReceived]    脚本日期: 04/09/2012 18:27:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-06-20>
-- Description:	<签收商品>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Order_ConfirmReceived]
@orderID int =null,--订单ID
--@orderNo varchar(50)=null,--订单编号
@opName varchar(20)=null,--操作人真实姓名
@operator int =null,--操作人ID
@OPRule varchar(50)=null,--操作角色 顾客，系统，商家,管理员
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorFlag=1
declare @paytype int,@prestatus int,@memberid int
select @paytype=paytype,@prestatus=status,@memberid =memberid from orders where orderid=@orderid

if @PreStatus<>6
begin
	select @errorFlag=1,@errorMsg='不能签收未发货的订单'
	return
end
else
begin
	if @OPRule='顾客' and @memberid<>@operator--会员签收订单要判断是否该会员的订单
	begin
		select @errorFlag=1,@errorMsg='无权签收别人的订单'
		return
	end

	begin try
		begin tran
		--向订单操作日志表中插入纪录
		if @OPRule='顾客'
		exec XpProc_OrderOpLog_Add @orderid,null,@opname,@operator,@OPRule,'顾客已签收','顾客已签收',7,1
		else
		exec XpProc_OrderOpLog_Add @orderid,null,@opname,@operator,@OPRule,'管理员签收订单','管理员签收订单',7,1

		update orders set status=7,receivetime=getdate() where orderid=@orderid
		--更新OrderProduct表中的COMMENTSTATUS为可评价
		update orderProduct set commentstatus=1 where orderid=@orderid
		select @errorFlag=0
	commit tran
	end try
	begin catch
		-- 捕捉错误
		rollback tran
		select @errorflag=1
		select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
		print @errormsg
		Return
	end catch
end
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Order_Delete]    脚本日期: 04/09/2012 18:27:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2012-01-10>
-- Description:	<取消订单的操作>
-- 删除订单，现在的生成的订单编号按当天的订单数量来生成的，所以不能从表中真实删除订单，要不生成的订单编号要重复
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Order_Delete]
@orderIDs varchar(8000)=null,--订单ID集
@adminid int =null,--操作人ID
@adminname varchar(50)=null,--操作人姓名
@realname varchar(20)=null,--操作人真实姓名
@OPRule varchar(50)=null,--操作角色 顾客，系统，商家,管理员
@OPDesc varchar(200)=null,--操作描述
@remark varchar(200)=null,--操作备注
@ip varchar(40)=null,--ip
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
begin try
select id,value as orderid into #t from dbo.SplitToTable_Func(@orderIDs,',')
begin tran
--更新相关的订单在orders表跟orderproduct表中的isdel状态
update o set isdel=1 from orders o,#t where o.orderid=#t.orderid
update sp set isdel=1 from orderproduct sp,#t where sp.orderid=#t.orderid
--写日志
--遍历游标
declare @orderid int,@description varchar(510)
declare orderid_items_cursor cursor for select orderid from #t 
open orderid_items_cursor                                                    
fetch next from orderid_items_cursor into @orderid
while @@fetch_status = 0                        
begin 
select @description='删除订单,订单ID为：'+cast(@orderid as varchar(20))
exec XpProc_EventLog_Insert @adminid,@adminname,@realname,6,62,@description,@ip
fetch next from orderid_items_cursor into @orderid
end
--遍历结束
close orderid_items_cursor                                                    
deallocate orderid_items_cursor
select @errorflag=0
select @errormsg='订单删除成功'
commit tran
end try
begin catch
-- 捕捉错误
rollback tran
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
end catch
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Order_Make]    脚本日期: 04/09/2012 18:27:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO











-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-05-20>
-- Description:	<添加新的订单>
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110809                              
content:                                
1.添加参数@membername,@password,@ztdAdminName用于后台管理员代下订单的时候自动创建会员账号

version:v1.2   
author:hakkas@qq.com                                
time:20110908                              
content:                                
1.增加成本价的记录 

version:v1.3   
author:hakkas@qq.com                                
time:20110922                              
content:                                
1.增加订单商品包装清单的记录 

version:v1.4   
author:hakkas@qq.com                                
time:20111011                              
content:                                
1.增加订单订单满额返券和单品返券功能  

version:v1.5   
author:hakkas@qq.com                                
time:20111026                              
content:                                
1.增加了地址簿的更改                            
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Order_Make]                 
@cartID nvarchar(36),  --购物车ID  
@memberID int, --会员ID 
@membername nvarchar(100)='',--会员账号
@password varchar(50)='',--密码
@rName nvarchar(20),--收货人姓名
@rEmail nvarchar(20),--收货人EMAIL
@rMobile nvarchar(20),--收货人联系手机
@rPhone nvarchar(20),--收货人联系电话
@rPostalcode nvarchar(20),--收货人邮编
@rAddress  nvarchar(100),--收货人详细地址
@topAreaID int,--省级ID
@subAreaID int,--市级ID
@thirdAreaID int,--县区级ID
@isSaveAddress int,--是否保存收货人地址到地址簿    
@shipAddressID int,--地址簿ID,
@payType int,--支付类型
@shippingID int,--配送方式
@shippingTime nvarchar(50), --送货时间
@code nvarchar(20),--代销人的代销号
@useadvpay tinyint,--是否使用预付款
@needInvoice tinyint,  --是否需要发票    
@invoiceType int,--发票类型
@invoiceHead nvarchar(50),--发票抬头
@isDetails tinyint,--发票内容是否为订单明细
@invoiceContent nvarchar(300),--发票内容
@taxRate decimal(18,2),--税金比例
@remark nvarchar(300),  --Remark 备注                                    
@orderType int,--订单类型:1为正常下订流程的订单,2为团购,3拍卖的订单,4为合并的订单                                                               
@addMethod int,   --AddMethod 下订方式,1是会员在线下的订单,2是管理员代订                                    
@ztdID int,   --取货门店ID   
@ztdNo varchar(20),   --取货门店编号 
@ztdAdminName varchar(100)='',--代下订单管理员账号                              
@ztdAdminID int=null, --代订管理员ID
@addIP varchar(50)='', --下订单人的IP地址
@supplierid int,--商家ID    
@errorMsg varchar(200)='' out,--错误信息提示        
@errorFlag int =0 out,--是否错误标识，<>0时，显示错误信息，并返回购物车界面 
@orderID int out, --订单ID
@orderNo nvarchar(30) out,--订单编号
@usedScore int out,--使用的总积分
@scoreSubMoney decimal(18,2) out,--积分抵扣的总金额
@usedAdvPayment decimal(18,2) out,--使用的预付款金额
@pmtPdtPrice decimal(18,2) out,--优惠后商品总价
@totalPrice decimal(18,2) out--订单总价
AS                                           
begin
--设置订单的默认信息       
select @errorMsg='',@errorFlag =1,@orderid=-1,@orderNo='',
@usedScore=0,@scoreSubMoney=0,@usedAdvPayment=0,@pmtPdtPrice=0,@totalPrice=0

Begin Try
print('商品地区销售限制判断')
select c.productid,isnull(p.city,@subAreaID) as city
into #city
from shoppingcart c
left join pdtcity p on c.productid=p.productid
where cartid=@cartid
select * into #o from #city where city=@subAreaID
delete #city from #city,#o o where #city.productid=o.productid
if exists(select productid from #city)
begin                                              
select @errorFlag=1,@errorMsg='购物车存在区域性销售限制的商品，且收货地址不在允许购买的区域内!'                                 
return @orderid  
end
 
print('构造地区ID字符串')
declare @addressID nvarchar(50)--地区ID
select @addressID=cast(@topAreaID as nvarchar(10))+','+cast(@subAreaID as nvarchar(10))+','+cast(@thirdAreaID as nvarchar(10))  
                
print('代下订单要先生成会员资料')     
if @memberid=-1 and isnull(@password,'')<>''
begin
exec XpProc_Member_Insert @membername,@password,@rEmail,0,0,'来电下单,代注册会员',null,null,@rPhone,null,null,null,null,null,@rName,null,0,null,null,0,0,1,'admin',0,1,null,null,0,@rMobile,@addressID,@rAddress,@rPostalcode,0,null,null,0,@addIP,@ztdAdminID,@ztdAdminName,@memberid output,@errorFlag output,@errorMsg output
if @errorflag=1
return @orderid
end
                                
print('新订单的生成..')                               
declare @orlPdtPrice decimal(18,2),--优惠前商品总价
@pmtSubPrice decimal(18,2),--享受的优惠总额
@subscore int,--获得的总积分
@shipPrice decimal(18,2),--配送价格
@taxPrice decimal(18,2),--税率
@weight decimal(18,2),--重量
@cltCharge decimal(18,2),--货到付款手续费
@quantity int,--商品数量
@isAgentF int,
@isShippingFree int,--是否免运费                                   
@sql nvarchar(1000),
@favourable nvarchar(500),--优惠信息
@couponmoney money,--优惠券优惠金额
@membermobile varchar(50),--会员手机号
@memberscore int,--会员当前可使用积分
@groupname nvarchar(20),--会员组名称
@discount nvarchar(20),--会员组折扣
@agentFContent nvarchar(100),
@status int,--订单状态
@ordertime datetime, --下订时间
@advancePayment decimal(18,2), --会员的电子账户余额
@needpaymoney decimal(18,2)--还需支付金额

--初始化变量值
select @isShippingFree=0,@shipPrice=20,@taxPrice=0,@cltCharge=0,@isAgentF=0,@agentFContent='',@favourable='',@status=0,@ordertime=getdate(),@advancePayment=0              

print('获取会员对应会员组享受的折扣')
select @membername=m.[name],@advancePayment=m.AdvancePayment,@memberscore=m.score,@membermobile=m.mobile,@groupname=mg.groupname,@discount=mg.discount 
from member m(nolock),membergroup mg(nolock) 
where m.groupid=mg.MemberGroupID and m.memberid=@memberid

print('商品信息')
select t.*                           
into #cart                           
from                                           
(                                          
select cartid,goodsid,productid,productno,marketprice,memberprice,weight,                                          
pmtprice,giftnumber quantity,subweight,submoney,lessmoney,                                          
pmtname,ruleid,basictype,subtype,giftremark remark,2 ptype,UseScore giftscore,2 GiftGetType,convert(nvarchar(20),'gift') PmtType                             
,g.pmtid,g.couponID,couponvalue=convert(money,0),coupongoodsmoney=convert(money,0),                                        
CouponMoney=convert(float,0),AvgCouponMoney=convert(float,0),
ProductSpecs='',isneedstowage=0,0 isdiscount,0 score,0 usescore,0 scoremoney,supplierid,suitid,null sort
--SystemOldPrice=convert(money,0),isPreDealed=0,isautochanged=0,                                    
from giftscart g(nolock)                                          
where cartid=@cartid  
and supplierid=@supplierid                                        
and addtime>dateadd(minute,-15,getdate()) --礼品购物车的商品必须在15分钟之内完成。                                          
and giftnumber>0                                          
union                                           
select cartid,goodsid,productid,productno,marketprice,memberprice,weight,                                          
pmtprice,quantity,subweight,submoney,lessmoney,                                          
pmtname,ruleid,basictype,subtype,remark,1 ptype,0 giftscore,0 GiftGetType,convert(nvarchar(20),'goods') PmtType                                         
,g.pmtid ,g.couponID,couponvalue=convert(money,0),coupongoodsmoney=convert(money,0),                                        
CouponMoney=convert(float,0),AvgCouponMoney=convert(float,0),
ProductSpecs,isneedstowage=0,isdiscount,score,0 usescore,ScoreMoney,supplierid,suitid,sort
--SystemOldPrice=convert(money,0),isPreDealed=0,isautochanged=0                                          
from GoodsCart g(nolock)                                          
where cartid=@cartid 
and supplierid=@supplierid                                         
and Quantity>0                                          
and addtime>dateadd(hour,-2,getdate())--购物车的商品必须在2小时之内完成。在这里已经存在着限前几名的抢购的问题。                                          
and (1=1 or (isnull(ruleid,0)>0 and addtime>dateadd(minute,-15,getdate())) )--促销商品必须在15分钟之内完成。                                          
) as t                                        
order by case when t.PmtType='goods' then 0 else 1 end --先添加正常商品信息再添加礼品信息

print('优惠券的使用')                          
select c.couponID--优惠券编号                                      
,p.couponvalue,--优惠券值                                       
coupongoodsmoney=sum(isnull(c.pmtprice,c.memberprice)*c.Quantity) --参与优惠券的商品总价                                       
into #couponDetail                                        
from  #cart c(nolock),CouponsMember m(nolock),Coupon p(nolock)                            
where isnull(c.couponID,0)>0                                        
and m.UID=c.couponID
and m.couponid=p.couponid                                        
group by c.couponID,p.couponvalue                                      
                                       
                                      
update c                                        
set CouponMoney=d.coupongoodsmoney, --参与优惠券的商品总价                                       
couponvalue=d.couponvalue,--优惠券值                                      
coupongoodsmoney=convert(float,case when d.couponvalue<d.coupongoodsmoney then d.couponvalue else d.coupongoodsmoney end *isnull(c.pmtprice,memberprice))/d.coupongoodsmoney*c.Quantity, --商品优惠金额                                       
AvgCouponMoney=convert(float,case when d.couponvalue<d.coupongoodsmoney then d.couponvalue else d.coupongoodsmoney end*isnull(c.pmtprice,memberprice))/d.coupongoodsmoney   --商品单价优惠金额                                      
from  #cart c(nolock),#couponDetail d(nolock)                                        
where d.couponID=c.couponID

/*=============================商品判断开始=================================*/
print('判断购物车中是否存在商品')
if not exists(select top 1 cartid from #cart)                                     
begin                                          
print('错误,购物车中不存在商品信息!')                                                
select @errorMsg='错误,购物车中不存在商品信息!'                  
,@errorFlag =1                                         
return @orderid                                          
end
/*=============================商品判断结束=================================*/

/*=====================礼品所需积分及限兑数量判断开始=======================*/
--判断积分
declare @TotalNeedScore int
select @TotalNeedScore=sum(giftscore*quantity) from #cart
if @TotalNeedScore>0 and @TotalNeedScore>@memberscore
begin
print('错误,没有足够的积分用于兑换礼品!')                                                
select @errorMsg='错误,没有足够的积分用于兑换礼品!'                  
,@errorFlag =1                                         
return @orderid  
end

--判断数量
declare @outlimitednum int
select @outlimitednum=count(1)
from gift g(nolock),GiftsCart c(nolock)
where g.productid=c.productid and isnull(c.ruleid,0)=0 and c.UseScore>0 and c.cartid=@cartid and c.giftnumber>case when g.limitednumber=0 then c.giftnumber else g.limitednumber end
if @outlimitednum>0
begin
print('错误,礼品兑换数量大于每人可兑换数量!')                                                
select @errorMsg='错误,礼品兑换数量大于每人可兑换数量!'                  
,@errorFlag =1                                         
return @orderid
end
/*=====================礼品所需积分及限兑数量判断结束========================*/

/*=============================库存控制开始=================================*/
begin tran
declare @cartnumber int,@EffectRows int 
print('商品库存控制')  
--统计商品数量                
select t.goodsid,Quantity=sum(t.Quantity)                  
into #groupcart                  
from #cart t(nolock)                             
group by t.goodsid 
                 
select @cartnumber=count(1) from #groupcart(nolock)                    
--更新商品goods表中的库存数量                  
update g set storage=g.Storage-c.quantity                  
from goods g(nolock),#groupcart c(nolock)                  
where                  
g.goodsid=c.goodsid                  
and g.Storage-c.Quantity>=0                 
                  
select @EffectRows=@@rowcount                  
                  
--有商品库存不足                  
if(@EffectRows<@cartnumber)             
begin                  
print('购物车的商品库存不足') 
select @errorflag=1, @errormsg='购物车的商品库存不足'                              
rollback 
return @orderid              
end

print('礼品库存控制')  
--统计礼品数量
select c.productid,sum(giftnumber) as quantity 
into #giftgroup 
from GiftsCart c(nolock) 
where isnull(c.ruleid,0)=0 and c.UseScore>0 and c.cartid=@cartid
group by productid

select @cartnumber=count(1) from #giftgroup(nolock)
--更新礼品库存
update g 
set g.AlreadyExchaged=g.AlreadyExchaged+c.quantity,g.storage=g.storage-c.quantity,g.exchagedmembers=g.exchagedmembers+1
from gift g,#giftgroup c
where g.productid=c.productid and g.Storage>c.quantity

select @EffectRows=@@rowcount 
--有礼品库存不足                  
if(@EffectRows<@cartnumber)             
begin                  
print('购物车中有礼品库存不足') 
select @errorflag=1, @errormsg='购物车中有礼品库存不足'                              
rollback 
return @orderid                
end         
/*=============================库存控制结束=================================*/                                            
--获取商品总价,总重量，总的赠送积分                                              
select                                               
@orlPdtPrice=sum(t.memberprice*t.Quantity),
@pmtPdtPrice=sum(submoney),
@pmtSubPrice=sum(LessMoney),
@couponmoney=sum(coupongoodsmoney),
@scoreSubMoney=sum(scoremoney),
@weight=sum(subweight),                                            
--@subscore=SUM(Score*t.Quantity),
@subscore=SUM(Score),
@usedscore=sum(t.usescore+t.giftscore*t.Quantity),                                              
@quantity=SUM(t.Quantity)                                              
from #cart t
--,Product p(nolock)                                               
--where p.ProductID = t.ProductID

--计算发票税金
print('计算发票税金')
select @taxPrice=@pmtPdtPrice*@taxRate	--发票税金等于商品总额乘于税率

/*=============================计算运费开始=================================*/ 
print('计算运费')
--select @shipprice=shipprice from ShipCart where cartid=@cartid and supplierid=@supplierid
exec dbo.XpProc_CartShipPrice_Get @cartid,@payType,@subAreaID,@shippingID,@weight,@pmtPdtPrice,@memberid,@supplierid,@shipprice out

/*=============================计算运费结束=================================*/ 

--统计订单总额
print('统计订单总额')
--订单总额等于优惠后的商品总价+配送费+发票税金-优惠券抵扣金额-积分抵扣金额
--select @totalPrice=isnull(@pmtPdtPrice,0)+isnull(@shipPrice,0)+isnull(@taxPrice,0)+isnull(@cltCharge,0)-isnull(@scoreSubMoney,0)-isnull(@advancePayment,0)
select @totalPrice=@pmtPdtPrice+isnull(@shipPrice,0)+@taxPrice-isnull(@couponmoney,0)-@scoreSubMoney

print('计算可使用预付款金额')
if @useadvpay=1
begin
if @advancePayment>=@totalPrice
select @usedAdvPayment=@totalPrice,@status=2
else
select @usedAdvPayment=@advancePayment,@status=case when @advancePayment>0 then 1 else 0 end
end
else
begin
select @usedAdvPayment=0
end

print('计算还需付款金额')
select @needpaymoney=@totalPrice-@usedAdvPayment

--如果还需付款金额小于等于0，订单状态要置为已付款
if @needpaymoney <=0
select @needpaymoney=0,@status=2
/*========================计算货到付款手续费开始=============================*/
print('计算货到付款手续费')
if(@payType=5)--采用货到付款方式才需要计算货到付款手续费
begin
	declare @fees decimal(18,2),--手续费
	@feesType int--0为净手续费，1为总金额的百分比
	select @fees=0,@feesType=0
	select @fees=Fees,@feesType=FeesType from ShippPay where ShippAreaID=@subAreaID and ShippID=@shippingID
	if(@feesType=0)
	begin
	select @cltCharge=isnull(@fees,0)
	end
	else
	begin
	select @fees=@fees/100
	select @cltCharge=@needpaymoney*isnull(@fees,0)
	end
end
/*========================计算货到付款手续费结束=============================*/ 

print('还需付款金额需要加上货到付款手续费')
select @needpaymoney=@needpaymoney+@cltCharge

--获取orderid                                              
--exec XpProc_MaxID_Get 'Orders',@orderid out

print('生成订单编号')
declare @ordercount nvarchar(10)
Select @ordercount=count(orderid)+1 from orders Where DateDiff(dd,ordertime,GetDate())=0  --当天订单总数
select @orderNo=replace(replace(convert(varchar(13),getdate(),120),'-',''),' ','')                                  
select @orderNo=replace(@orderNo,'.','')   --转为2011012316                                    
select @orderNo=right(@orderNo,8) + right('000'+ cast(@ordercount as nvarchar(10)),4) --取时间的后8位+当天订单总数(若订单总数长度超过4,只取最后的4位) 
/*=============================订单生成=================================*/
insert into orders(
--OrderID,
MemberID,
OrderTime,
ShipTime,
BuyerName,
BuyerPhone,
BuyerMobile,
BuyerEmail,
BuyerAddress,
BuyerPostalcode,
ReceiverName,
ReceiverPhone,
ReceiverMobile,
ReceiverEmail,
ReceiverAddress,
ReceiverPostalcode,
Remark,
TotalPrice,
NeedPayMoney,
LessMoney,
ProductPrice,
CustomItemPrice,
Discount,
ShipPrice,
AdvancePayment,
PaymentType,
ShippingType,
Score,
Weight,
Quantity,
NeedInvoice,
TaxPrice,
CltCharge,
PayType,
Status,
ManageHistory,
LastModify,
OrderNo,
Code,
IsAgentF,
IsAgentFContent,
IsShippingFree,
Type,
Favourable,
ZtdNo,
IsToErp,
OrderType,
IsToMessage,
AddMethod,
AddressID,
UsedScore,
ScoreAmount,
CouponValue,
SupplierID
) 
values
(
--@orderID,
@memberID,
@ordertime,
@shippingTime,
'',
'',
'',
'',
'',
'',
@rName,
@rPhone,
@rMobile,
@rEmail,
@rAddress,
@rPostalcode,
@remark,
@totalPrice,--订单总额
@needpaymoney,--还需支付金额
@pmtSubPrice,--订单优惠金额
@pmtPdtPrice,--商品总额
0,--配件价格
@discount,
@shipPrice,
@usedAdvPayment,
0,--以前是paymentID,现在不用存支付方式ID,只需要存payType
@shippingID,
@subscore,
@weight,
@quantity,
@needInvoice,
@taxPrice,
@cltCharge,
@payType,
@status,
'',--订单管理日志
0,--最后更新时间
@orderNo,--订单编号
@code,
@isAgentF,
@agentFContent,
@isShippingFree,
@orderType,
@favourable,
@ztdNo,
0,
0,
0,
1,
@addressID,
@usedScore,
@scoreSubMoney,
@couponmoney,
@supplierid
)   
select @orderID=@@Identity                                        
/*=============================订单生成结束=================================*/
/*===========================订单明细生成开始===============================*/
--合并套餐商品中重复的商品
--按商品ID，货品ID分组统计单项总数量，单项总金额，单项优惠总金额，单项优惠券抵扣总金额
select productid,goodsid,sum(quantity) quantity,sum(submoney) submoney,sum(lessmoney) lessmoney,sum(CouponGoodsMoney) CouponGoodsMoney
into #t
from #cart
group by productid,goodsid
--删除重复的商品
;with g
as (
select *,
ROW_NUMBER() over (partition by productid,goodsid order by sort) as rn
from #cart
)
--select * from g
delete g where rn > 1
--更新单项总数量，单项总金额，单项优惠总金额，单项优惠券抵扣总金额
update c set c.quantity=t.quantity,c.submoney=t.submoney,c.lessmoney=t.lessmoney,c.CouponGoodsMoney=t.CouponGoodsMoney
from #cart c,#t t
where c.productid=t.productid and c.goodsid=t.goodsid


--获取购物车中的商品信息                                              
declare @ProductID int,@GoodsName nvarchar(255),@ProductNo nvarchar(50),@packinglist varchar(500),@CostPrice decimal(18,2),
@MemberPrice decimal(18,2),@pmtprice decimal(18,2),@SubMoney decimal(18,2),@LessMoney decimal(18,2),@PScore int,                          
@ThumbnailImg nvarchar(255),@IsDiscount tinyint,@PQuantity int,@ProductSpecs nvarchar(200),@CategoryID int,@BrandID int,
@GoodsID int,@UseScore int,@ptype int,@giftscore int,@giftgettype int,@PmtType nvarchar(20),
@StowageID int,@IsOfferInvoice tinyint                                                                                
declare @ruleid int,--规则ID                                          
@RuleName  nvarchar(200),--规则名称                                          
@pmtid  int,--促销ID                                          
@pmtname nvarchar(200) ,--促销活动名称                                    
--@PromotionProductType  varchar(50),                                        
@CouponsMemberID int,@couponvalue money,@coupongoodsmoney float,@AvgCouponMoney float--优惠信息                                         
,@isNeedStowage int, --是否需要库存  
@goodsremark varchar(200)                
                                          
declare cart_items_cursor cursor for                                              
select                                              
p.ProductID,                                          
g.GoodsName,                                              
--p.ProductNo,                                
g.goodsno,
p.PackingList,
p.CostPrice, 
g.MemberPrice,                                     
isnull(sc.pmtprice,sc.memberprice) pmtprice,  
isnull(sc.submoney,0) Submoney,
isnull(sc.LessMoney,0) LessMoney,                          
sc.Score,                                                                          
p.IsDiscount,                                              
sc.Quantity,                                                                          
sc.ProductSpecs,                                           
p.ThumbnailImg,                                                
p.CategoryID,                                              
p.BrandID,                                              
g.GoodsID,
sc.giftscore,
sc.pmttype,--'gift' or 'goods'
sc.ptype,
sc.giftscore,
sc.giftgettype, 
0 StowageID,                                           
p.IsOfferInvoice,
ruleid ,--规则ID                                          
'' RuleName ,--规则名称                                          
sc.pmtid  ,--促销ID                                          
sc.PmtName ,--促销活动名称                                                                       
sc.CouponID,
sc.couponvalue,
sc.coupongoodsmoney,sc.AvgCouponMoney,--优惠券信息
sc.isNeedStowage,--是否需要库存
sc.remark                                                                                      
from Product as p(nolock),#cart as sc(nolock),Goods as g(nolock)                                               
where                              
p.ProductID = sc.ProductID                                                 
AND sc.GoodsID = g.GoodsID                                               
and g.ProductID = p.ProductID                                               
--AND sc.CartID = @cartID  
order by sc.sort                                             
                                                                                            
open cart_items_cursor                                              
fetch next from cart_items_cursor into                                           
@ProductID,@GoodsName,@ProductNo,@packinglist,@CostPrice,
@MemberPrice,@pmtprice,@submoney,@LessMoney,@PScore,
@IsDiscount,@PQuantity,@ProductSpecs,@ThumbnailImg,@CategoryID,@BrandID,@GoodsID,@UseScore,@PmtType,
@ptype,@giftscore,@giftgettype,@StowageID,@IsOfferInvoice,                                            
@ruleid ,--规则ID                                          
@RuleName ,--规则名称                                          
@Pmtid,--促销ID                                          
@pmtname ,--促销活动名称                                          
@CouponsMemberID,                                        
@couponvalue,
@coupongoodsmoney,@AvgCouponMoney,                                  
@isNeedStowage,--是否需要库存  
@goodsremark   
                                           
 --开始循环购物车内的商品
print('开始循环购物车内的商品')                                              
while @@fetch_status = 0
begin                                             
--将购物车中的当前商品添加到OrderProduct                                              
--declare @orderproductid int                                              
--exec XpProc_MaxID_Get 'OrderProduct',@orderproductid out --ID                                             
--print '商品ID' + cast(@ProductID as nvarchar(10)) + ',商品数量:' + cast(@PQuantity as nvarchar(10))                                             
insert into OrderProduct                                               
(                                              
--OrderProductID,
OrderID,OrderNo,ProductID,Items,Quantity,CostPrice,MemberPrice,--1                                              
UnitPrice,SubPrice,ItemsPrice,LessMoney,Remark,IsDiscount, --2                                             
ProductName,ProductSpecs,ProductNo,ThumbnailImg,CategoryID, --3                                             
BrandID,GoodsID,UsedScore,Ptype,GiftScore,GiftGetType,  --4
IsOfferInvoice,                                          
RuleID,--规则ID                                          
RuleName,--规则名称                                          
PmtID,--促销ID                                          
PmtName,--促销活动名称                                         
CouponsMemberID,
CouponValue,
CouponGoodsMoney,
AvgCouponMoney,--优惠券信息 
IsNeedStowage,--是否需要库存  
SupplierID,--商家ID  
Stockout,--未发货数量
MemberID,--会员ID
OrderTime,--购买时间 
Score,--赠送积分  
PackingList --包装清单     
)                                              
values                                      
(                                              
--@orderproductid,
@OrderID,@OrderNo,@ProductID,'',@PQuantity,@CostPrice,@MemberPrice,--1                                            
@pmtprice,@submoney,0,@LessMoney,@goodsremark,@IsDiscount,--2                
@GoodsName,@ProductSpecs,@ProductNo,@ThumbnailImg,  @CategoryID,--3                                              
@BrandID, @GoodsID,0,@ptype,@giftscore,@giftgettype,  --4                                            
@IsOfferInvoice,                                           
@ruleid ,--规则ID                                          
@RuleName ,--规则名称                                          
@PmtID,--促销ID              
@PmtName ,--促销活动名称                                         
@CouponsMemberID,
@couponvalue,
@coupongoodsmoney,
@AvgCouponMoney,--优惠券信息                              
@IsNeedStowage,
@SupplierID,
@PQuantity,
@MemberID,
@ordertime,
@pscore,
@packinglist    
)

--更改促销商品的剩余数量
update pmtgoods set balance=balance-@Quantity where ruleid=@ruleid and productid=@productid and goodsid=@goodsid

--记录参与的促销情况 
if isnull(@ruleid,0)>0  
begin                                                                            
insert into MemberBookPmtGoods(                                          
type,memberid,membername,orderid,orderno,                           
productid,ProductNo,ProductName,GoodsID,Quantity,ReturnQuantity,                                          
RuleID,RuleName,PmtID,PmtName,Status,SupplierID)                                                                              
select @PmtType,@memberid,@membername,@OrderID,@OrderNo,                                          
@ProductID,@ProductNo,@GoodsName,@GoodsID,@PQuantity,0,                                          
@ruleID,@RuleName,@PmtID,@PmtName,1,@SupplierID                                          
--from orders o(nolock)                                          
--where 
--o.orderid=@OrderID                                          
--and isnull(@ruleID,0)>0
end

fetch next from cart_items_cursor into                                           
@ProductID,@GoodsName,@ProductNo,@packinglist,@CostPrice,
@MemberPrice,@pmtprice,@submoney,@LessMoney,@PScore,@IsDiscount,@PQuantity,@ProductSpecs,
@ThumbnailImg,@CategoryID,@BrandID,@GoodsID,@UseScore,@PmtType,
@ptype,@giftscore,@giftgettype,@StowageID,@IsOfferInvoice,                                            
@ruleid ,--规则ID                                          
@RuleName ,--规则名称                                          
@Pmtid,--促销ID                                          
@pmtname ,--促销活动名称                                          
@CouponsMemberID,                                        
@couponvalue,
@coupongoodsmoney,@AvgCouponMoney,                                  
@isNeedStowage,--是否需要库存 
@goodsremark
end                                                              
--购物车商品循环结束                                           
print '购物车商品循环结束'                                              
close cart_items_cursor                                              
deallocate cart_items_cursor
/*===========================订单明细生成结束===============================*/

/*=========================记录结算明细开始==============================*/
print('计算佣金并记录订单结算明细')
/*改由收款的时候记录
declare @yongjin money,@bprate float
select @bprate=BPRate from supplier where supplierid=@supplierid
select @yongjin = round(@pmtPdtPrice*@bprate,2)
exec XpProc_FinanceDetail_Insert @ordertime,@orderid,@orderno,@totalPrice,0,@yongjin,@supplierid,0
*/
/*=========================记录结算明细结束==============================*/


/*=========================记录发票信息开始==============================*/                          
print('记录发票信息')
if @needInvoice=1
begin
exec XpProc_OrderInvoice_Insert @orderid,@invoiceType,@invoiceHead,@isDetails,@invoiceContent,@memberid
end
/*=========================记录发票信息结束==============================*/

/*=========================记录套装购买记录开始==============================*/
insert into memberbooksuit(cartid,memberid,membername,suitid,suitname,price,score,orderid,orderno,quantity,ordertime,supplierid,ip,status)
select cartid=@cartid,@memberid,@membername,suitid,suitname,memberprice,score,orderid=@orderid,orderno=@orderno,quantity,ordertime=@ordertime,supplierid=@supplierid,@addIP,1
from suitscart where cartid=@cartid
/*=========================记录套装购买记录结束==============================*/

/*=========================扣减积分及记录兑换记录开始==============================*/
--记录礼品兑换记录                                                                               
insert into MemberExchangeGifts(                                          
memberid,membername,orderid,orderno,                           
productid,ProductNo,ProductName,GoodsID,Quantity,Status,SupplierID
)                                                                              
select @memberid,@membername,@OrderID,@OrderNo,                                          
g.productid,g.productno,g.ProductName,g.GoodsID,g.giftnumber,1,g.supplierid                                                                           
from giftscart g(nolock)                                          
where isnull(g.ruleid,0)=0 and g.UseScore>0 and g.cartid=@cartid
--记录积分使用记录
exec XpProc_ScoreLog_Insert @memberid,@membermobile,@TotalNeedScore,-1,1,0,null,'兑换礼品',@orderid,'兑换礼品扣减积分','兑换礼品扣减积分',@addIP,null,null,@memberid,@membername
/*=========================扣减积分及记录兑换记录结束==============================*/

/*=========================下订单预赠送积分开始==============================*/                          
print('预送积分暂时不做')
/*=========================下订单预赠送积分结束==============================*/                                          
                          
/*=========================使用及赠送优惠券开始==============================*/
print('更新优惠券信息')                                                                              
--使用优惠券,需要更新优惠券信息                                        
select distinct p.orderid,p.CouponsMemberID                                        
into #newordercoupon                                        
from orderproduct p(nolock)                                        
where p.orderid=@orderid                                        
--更新优惠券的使用情况                                        
update m                                        
set Status=case when m.ispublic=1 then 1 else 0 end,UsedTimes=UsedTimes+1,IsUsed=case when m.ispublic=1 then 0 else 1 end,UsedTime=getdate(),UseUserID=@memberid,m.OrderID=n.OrderID,m.orderno=@orderNo                                      
from                                         
CouponsMember m(nolock),#newordercoupon n(nolock)                                        
where n.CouponsMemberID=m.UID                                        
--添加使用优惠券记录                                        
insert into CouponsUsedItems(OrderID,OrderNo,CouponID,CouponName,CouponCode,UseUserID,SupplierID)              
select n.OrderID,@orderno,m.UID,c.CouponName,m.CouponCode,@memberid,@supplierid                                        
from #newordercoupon n(nolock),Coupon c(nolock),CouponsMember m(nolock)
where n.CouponsMemberID=m.UID
and m.CouponID = c.CouponID

--记录待赠送的优惠券
select p.*
into #c
from
(
--订单满额返券
select c.couponid,c.number,c.number as subnumber,c.Validity,r.ruleid,r.rulename,null as productid,null as goodsid
from pmtrule r(nolock),pmtcoupons c(nolock)
where r.basictype='orders' and r.subtype='coupon' and @pmtpdtprice between minvalue and maxvalue and getdate() between BeginTime and EndTime and r.ruleid=c.ruleid and r.supplierid=@supplierid
union
--单品返券
select c.couponid,c.number,c.number*t.quantity as subnumber,c.Validity,r.ruleid,r.rulename,g.productid,g.goodsid
from #cart t,pmtrule r(nolock),pmtgoods g(nolock),pmtcoupons c(nolock)
where t.productid=g.productid and g.ruleid=r.ruleid and r.basictype='goods' and r.subtype='coupon' and getdate() between BeginTime and EndTime and c.ruleid=r.ruleid and r.supplierid=@supplierid
) as p

insert into ordercoupon(memberid,membername,cartid,orderid,orderno,couponid,couponname,couponvalue,suittype,suitvalue,
MinMoney,begintime,endtime,Validity,number,subnumber,productid,goodsid,ruleid,rulename,supplierid,sendreason,ip,status)
select @memberid,@membername,@cartid,@orderid,@orderno,c.couponid,c.couponname,c.couponvalue,c.suittype,c.suitvalue,
c.minmoney,c.begintime,c.endtime,t.Validity,t.number,t.subnumber,t.productid,t.goodsid,t.ruleid,t.rulename,@supplierid,t.rulename,@addIP,0 as status
from #c t,coupon c(nolock)
where t.couponid=c.couponid
/*=========================使用及赠送优惠券结束==============================*/ 

/*========================扣减预付款开始==============================*/
if @useadvpay=1 and @usedAdvPayment>0
begin
declare @usedremark varchar(100)
select @usedremark = '电子账户余额支付订单:'+@orderno
select  @usedAdvPayment=-@usedAdvPayment   
exec XpProc_AdvancePayment_Add @memberid,@membername,@usedAdvPayment,-1,'system',@usedremark,@errorflag out,@errormsg out
end
/*========================扣减预付款开始==============================*/     

/*========================更新地址簿开始==============================*/
if @shipAddressID>0
begin
exec XpProc_ReceiverAddress_Update @shipAddressID,@rName,@rAddress,@rPostalcode,@rPhone,@rMobile,@MemberID,@AddressID,@rEmail                              
end
else
begin
if @isSaveAddress=1
exec XpProc_ReceiverAddress_Insert @rName,@rAddress,@rPostalcode,@rPhone,@rMobile,@MemberID,@AddressID,@rEmail
end
/*========================更新地址簿结束==============================*/ 
                                       
 --删除购物车内容                                                                       
delete from ShoppingCart where CartID=@cartID and supplierid=@supplierid 
delete from suitscart where CartID=@cartID and supplierid=@supplierid                                    
delete from GoodsCart where CartID=@cartID and supplierid=@supplierid                                         
delete from GiftsCart where CartID=@cartID and supplierid=@supplierid                                        
delete from CouponCart where CartID=@cartID and supplierid=@supplierid

/*=========================记录订单生成日志开始==============================*/ 
if @addMethod=2
--管理员代下单
exec XpProc_OrderOpLog_Add @orderid,@orderno,@ztdAdminName,@ztdAdminID,'管理员','管理员代下单','管理员代下单',0,1
else
--会员自己下单
exec XpProc_OrderOpLog_Add @orderid,@orderno,@membername,@memberid,'顾客','顾客下单','顾客下单',0,1
--如果使用了预付款要插入订单支付日志
if(@usedAdvPayment<>0)
exec XpProc_OrderOpLog_Add @orderid,@orderno,@membername,@memberid,'顾客','顾客电子账户余额支付订单','顾客电子账户余额支付订单',@status,1
/*=========================记录订单生成日志结束==============================*/  
select @errorflag=0,@errormsg=''
commit  
End Try

Begin Catch
--回滚事务
rollback
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1,@orderid=-1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch                                      
end


















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Order_Refund]    脚本日期: 04/09/2012 18:27:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-06-24>
-- Description:	<管理员退款>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Order_Refund]
	@orderID int =null,--订单ID
	@orderNo varchar(50)=null,--订单编号
	@opname varchar(20)=null,--操作人真实姓名
	@operator int =null,--操作人ID
	@OPRule varchar(50)=null,--操作角色 顾客，系统，商家,管理员
	@ip varchar(40)=null,--操作员Ip

	--退款单数据
	@payerName varchar(50)=null,--付款人姓名
	@payBank varchar(50)=null,--付款银行
	@payBankAccount varchar(50)=null,--付款账号
	@bank varchar(50)=NULL,--收款银行
	@bankAccount varchar(50)=NULL,--收款账号
	@payTime datetime=NULL,--付款时间
	@payMethod int=null,--支付类型
	@paymentName varchar(50)=null,--支付方式
	@money decimal(18,2)=NULL,--付款金额
	@outTradeNo varchar(50)=NULL, --外部交易号
	@status int=null,
	@remark varchar(255)=null,
	@errorFlag int output,
	@errorMsg varchar(200) output
AS
BEGIN
	select @errorFlag=1
	declare @paytype int,@prestatus int,@operatorid int, @sendtime datetime,@ordertime datetime,@productprice decimal,@supplierid int
	if @OrderNo is NULL
	begin
	select @PreStatus=status ,@orderno=orderno ,@paytype=paytype,@operatorid=memberid,@sendtime=sendtime,@ordertime=ordertime,@productprice=productprice,@supplierid=supplierid
	from orders(nolock)
	where orderid=@OrderID
	end
	else
	begin
	select @PreStatus=status ,@OrderID=orderid ,@paytype=paytype,@operatorid=memberid,@sendtime=sendtime,@ordertime=ordertime,@productprice=productprice,@supplierid=supplierid
	from orders(nolock)
	where orderno=@OrderNo
	end

begin try
begin tran
	if(@PreStatus<>8)
	begin
	set @errorFlag=1
	set @errorMsg='当前的订单状态还不能退款'
	end
	else
	begin
	exec XpProc_OrderOpLog_Add @orderid,null,@opname,@operator,@OPRule,'管理员退还货款','管理员退还货款',11,1
	if(@sendtime is not null)--货已发出的情况,这个是因为退货而产生的退款，要在订单结算明细里插入一条记录表示因退货而产生了退款。
	--退货的原因多种，1是顾客自身的原因，2是商家的原因，严格来说，这二种不同的情况产生的退货费用是不同的，这里没有严格区分开。
	begin
	--记录订单结算明细,只退商品金额，运费，税金等不退
	exec XpProc_FinanceDetail_Insert @ordertime,@orderid,@orderno,0,@productprice,0,@supplierid,1
	select @money=@productprice
	end
	--返回用户花费的积分?
	declare @usedscore decimal(18,2),@giftscores decimal(18,2),@memberid int
	select @memberid=memberid,@usedscore =isnull(usedscore,0) from orders where orderid=@orderid
	select @giftscores=isnull(sum(GiftScore*Quantity),0) from OrderProduct where OrderID =@orderid and Ptype = 2 and GiftGetType = 1
	if(@usedscore+@giftscores)>0--用户花费的积分>0
	begin
	declare @ScoreType varchar(50),@FromID varchar(100),@FromRemark varchar(100),@score decimal(18,2),@GenerateTime datetime,@addtime datetime
	set @score=@usedscore+@giftscores
	set @ScoreType='退款返还消费的积分'
--	set @FromID='退款订单编号['+@orderno+']'
	set @FromID=@orderid
	set @FromRemark='退款[' + @orderno+ ']返还消费的积分'
	set @Remark='退款[' + @orderno+ ']返还消费的积分'
	set @GenerateTime=getDate()
	set @addtime=getDate()
	exec XpProc_ScoreLog_Insert @memberid,null,@score,1,0,0,null,@ScoreType,@FromID,@FromRemark,@Remark,@ip,@GenerateTime,@addtime,@operator,@opname
	end
	--插入退款记录
	INSERT ReceivePay(
	OrderNo, Bank, BankAccount, PayerName, [Money], PayMethod,PaymentName, WorkPeople,  
	PayTime, Status, Remark, IsReceive,OutTradeNo, PayBank, PayBankAccount)
	VALUES (
	@OrderNo, @bank, @bankAccount, @payerName, @money, @payMethod,@paymentname, @opname, 
	@payTime,COALESCE(@Status, (1)), @remark, 0, @outTradeNo, @payBank, @payBankAccount)
	
	update orders set status=11,canceltime=getdate() where orderid=@orderid
	set @errorFlag=0
	set @errorMsg='交易失败,已退款'
	end
commit tran
end try
Begin Catch
rollback tran
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return 0
End Catch
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Order_SendGoods]    脚本日期: 04/09/2012 18:27:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-06-16>
-- Description:	<处理商家发货>
-- =============================================
Create PROCEDURE [dbo].[XpProc_Order_SendGoods]
--	@orderNo varchar(50)=null,--订单编号
	@orderID int=null,--订单编号
	@shippingID int=null,--顾客选择的快递公司ID
	@ExpressName nvarchar(50)=null, --商家发货用的快递公司
	@transNum nvarchar(50)=null, --运单号
	@queryUrl varchar(400)=null,--快件查询接口
	@ShippingPrice decimal(18,0)=null, --发货费用
	@ReceiverName nvarchar(50)=null, --收货人
	@ReceiverEmail nvarchar(50)=null, --邮箱
	@receiverPhone nvarchar(50)=null, --电话
	@ReceiverPostalcode nvarchar(10)=null, --邮编
	@ReceiverAddress nvarchar(255)=null, --地址
	@shippingRemark nvarchar(255)=null, --发货备注
	
	@opname varchar(50)=null,--操作人真实姓名
	@operator int=null,--操作人ID	
	@remark varchar(255)=NULL,--备注
	@OPRule varchar(50)=null,--操作角色 顾客，系统，商家,管理员

	@pdtQuantity varchar(8000)=Null,--一个订单中已发货的商品数量,格式为'1,2,3,4,5'
	@pdtIDs varchar(8000)=Null,--发货的商品ID的集
	@goodsIDs varchar(8000)=Null,--发货的商品货品ID的集
	@pdtNames varchar(8000)=Null,--发货的商品名的集
	@flag int, --标识是部分还是全部发货，0部分发货，1全部发货
	@errorFlag int=1 output,
	@errorMsg varchar(200)=null output
AS
BEGIN
select @errorFlag=1
select @errorMsg='产生错误了'
begin try
begin tran
declare @paytype int,@prestatus int,@membername nvarchar(100),@orderno varchar(50),@memberid int
select @paytype=paytype,@prestatus=orders.status,@membername=[name] ,@orderno=orderNo ,@memberid=orders.memberid from orders,member where OrderID=@orderID and orders.memberid=member.memberid
declare @deliverinfo varchar(300)
if @paytype<>5 and @paytype<>6--非货到付款订单
begin
	if @prestatus=2 or @prestatus=4 or @prestatus=5
	begin
		if(@flag=1)--全部发货
		begin
			select productid as pdtid,goodsid ,productname as pdtname,quantity as pdtquantity into #temp1 from orderproduct where
			orderid =@orderid
			--更新OrderProduct表中的Stockout字段的值
			update orderproduct set stockout=0 where orderid=@orderID
			
			--向订单发货表中插入记录
			insert shippinginvoice(OrderID,MemberName,ShippingPrice,ShippingID,ShipCompanyName,ShippingNo,
			ReceiverName,Address,PostalCode,Tel,Email,Admin,AddTime,Remark,Status,IsReturn,ProductID,ProductName,Quantity)
			select @orderid,@memberName,@Shippingprice,@shippingid,@ExpressName,@transNum,@ReceiverName,@ReceiverAddress,
			@ReceiverPostalCode,@receiverPhone, @ReceiverEmail,@opname,getDate(),@shippingRemark,1,0,goodsid,pdtName,pdtQuantity from #temp1

			exec XpProc_Storage_Add @orderid ,@goodsIDs,@pdtQuantity,'发货',-1,@memberid			
			--向订单操作日志表中插入纪录
			set @deliverinfo='商家已发货。物流公司信息：'+@ExpressName+'  物流单号：'+@transNum+' 快件查询 <a href='''+@queryUrl+''' target=_blank>'+@queryUrl+'</a>'
			exec XpProc_OrderOpLog_Add null,@orderno,@opname,@operator,@OPRule,@deliverinfo,'商家已发货',6,1
			--更新订单状态
			update orders set status=6,sendtime=getdate() where orderid=@orderid 
			select @errorflag=0
			select @errorMsg='全部商品已发出'
		end
		else --这里是部分发货
		begin
			--由@pdtquantity,@pdtIDs,@pdtNames三个串生成一个具有产品ID，产品名称，发货数量的临时表
			select a.value as 'pdtID',b.value as 'goodsID',c.value as 'pdtName',d.value as 'pdtQuantity' into #temp2
			from
			(select * from dbo.SplitToTable_Func(@pdtIDs,','))a,
			(select *from dbo.SplitToTable_Func(@goodsIDs,','))b,
			(select *from dbo.SplitToTable_Func(@pdtNames,','))c,
			(select *from dbo.func_splitint2(@pdtQuantity))d
			where a.id=b.id and a.id=c.id and a.id=d.id

			--更新OrderProduct表中的Stockout字段的值
			update orderproduct set stockout=stockout-pdtQuantity from orderproduct,#temp2 
			where orderproduct.goodsid=#temp2.goodsid and orderid=@orderID

			--向Storage表中插入商品出入库纪录
			exec XpProc_Storage_Add @orderid ,@goodsIDs,@pdtQuantity,'发货',-1,@memberid			

			--向订单发货表中插入记录
			insert shippinginvoice(OrderID,MemberName,ShippingPrice,ShippingID,ShipCompanyName,ShippingNo,
			ReceiverName,Address,PostalCode,Tel,Email,Admin,AddTime,Remark,Status,IsReturn,ProductID,ProductName,Quantity)
			select @orderid,@memberName,@Shippingprice,@shippingid,@ExpressName,@transNum,@ReceiverName,@ReceiverAddress,
			@ReceiverPostalCode,@receiverPhone, @ReceiverEmail,@opname,getDate(),@shippingRemark,1,0,goodsid,pdtName,pdtQuantity from #temp2 where #temp2.pdtQuantity>0

			--此时可能所有的商品都已发出去了
			if exists(select orderid from orderproduct where stockout>0 and orderid=@orderid)--这个订单中的所有的商品都已经发出了
			begin 
				--向订单操作日志表中插入纪录
				set @deliverinfo='商家已部分发货。物流公司信息：'+@ExpressName+'  物流单号：'+@transNum+' 快件查询 <a href='''+@queryUrl+''' target=_blank>'+@queryUrl+'</a>'
				exec XpProc_OrderOpLog_Add null,@orderno,@opname,@operator,@OPRule,@deliverinfo,'商家已部分发货',5,1
				update orders set Status=5 where orderid=@orderid
				select @errorMsg='部分商品已发出'
			end
			else
			begin
				--向订单操作日志表中插入纪录
			    set @deliverinfo='商家已发出剩余商品。物流公司信息：'+@ExpressName+'  物流单号：'+@transNum+' 快件查询 <a href='''+@queryUrl+''' target=_blank>'+@queryUrl+'</a>'
				exec XpProc_OrderOpLog_Add null,@orderno,@opname,@operator,@OPRule,@deliverinfo,'商家已发出剩余商品',6,1
				--更新订单表的状态
				update orders set status=6,sendtime=getdate() where orderid=@orderid 
				select @errorMsg='剩余商品已发出'
			end
			select @errorFlag=0
		end	
	end
end
else --货到付款订单,没有部分发货的情况
begin
	select productid as pdtid,goodsid ,productname as pdtname,quantity as pdtquantity into #temp3 from orderproduct where
	orderid =@orderid
	--向订单发货表中插入记录
	insert shippinginvoice(OrderID,MemberName,ShippingPrice,ShippingID,ShipCompanyName,ShippingNo,
	ReceiverName,Address,PostalCode,Tel,Email,Admin,Addtime,Remark,Status,IsReturn,ProductID,ProductName,Quantity)
	select @orderid,@memberName,@Shippingprice,@shippingid,@ExpressName,@transNum,@ReceiverName,@ReceiverAddress,
	@ReceiverPostalCode,@receiverPhone, @ReceiverEmail,@opname,getDate(),@shippingRemark,1,0,goodsid,pdtName,pdtQuantity from #temp3

	--更新OrderProduct表中的Stockout字段的值
	update orderproduct set stockout=0 where orderid=@orderID

	--向Storage表中插入商品出入库纪录
	exec XpProc_Storage_Add @orderid ,@goodsIDs,@pdtQuantity,'发货',-1,@memberid			

	--向订单操作日志表中插入纪录
	if(@paytype=5)--货到付款
	begin
		set @deliverinfo='商家已发货。物流公司信息：'+@ExpressName+'  物流单号：'+@transNum+' 快件查询 <a href='''+@queryUrl+''' target=_blank>'+@queryUrl+'</a>'
		exec XpProc_OrderOpLog_Add null,@orderno,@opname,@operator,@OPRule,@deliverinfo,'商家已发货',6,1
		update orders set status=6,sendtime=getdate() where orderid=@orderid 
		select @errorFlag=0
		select @errorMsg='全部商品已发出'
	end
	else--门店自提
	begin
		exec XpProc_OrderOpLog_Add null,@orderno,@opname,@operator,@OPRule,'顾客已提货','顾客已提货',7,1
		update orders set status=7,sendtime=getdate(),receivetime=getdate() where orderid=@orderid 
		select @errorFlag=0
		select @errorMsg='顾客已提货'
	end
end
commit tran
end try
begin catch
	select @errorFlag=1
	select @errormsg=error_Message()
	rollback tran
end catch
END





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Order_Update]    脚本日期: 04/09/2012 18:27:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2012-01-10>
-- Description:	<修改Orders表中的某个字段的值，并加入订单日志>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Order_Update]
@orderID int=null,--订单ID
@operator int =null,--操作人ID
@opname varchar(20)=null,--操作人真实姓名
@OPRule varchar(50)=null,--操作角色 顾客，系统，商家,管理员
@OPDesc varchar(200)=null,--操作描述
@remark varchar(200)=null,--操作备注
@ip varchar(40)=null,--ip
@field varchar(200),--要修改的订单Orders表中的某个字段
@value varchar(200),--要修改的订单Orders表中的某个字段的值
@isappend bit,--@value是覆盖还是附加到原有值上去，1是附加，0是覆盖
@where varchar(1000),--只有订单符合这个条件才可以修改这个订单
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
begin try
if not exists(select orderid from orders where orderid=@orderid and 1=@where)
begin
select @errorflag=1
select @errormsg ='不能修改当前的订单'
return
end
begin tran
if  exists(select status from orders where orderid=@orderid and 1=@where)
begin
select @errorflag=1
select @errormsg ='不能修改当前的订单'
return
end
declare @OPStatus int --操作后订单的状态
declare @status int--操作前订单的状态
declare @oldremark varchar(max)
select @opstatus=status,@status=status,@oldremark=@field from orders where orderid=@orderid and 1=@where

if @isappend=0
update orders set @field=@value where orderid=@orderid
else
update orders set @field=@field+@value where orderid=@orderid

--写订单日志


select @remark='修改订单附言'
select @opdesc=@remark+'（修改前订单附言：；修改后订单附言：'
exec XpProc_OrderOpLog_Add @orderid,null,@opname,@operator,'管理员',@opdesc,@remark,@status,1


exec XpProc_OrderOpLog_Add @orderid,null,@OPName,@operator,@OPRule,@remark,@remark,3,1

select @errorflag=0
select @errormsg='订单修改成功'
commit tran
end try
begin catch
-- 捕捉错误
rollback tran
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
end catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderCitic_Select]    脚本日期: 04/09/2012 18:27:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2012-03-30>
-- Description:	<统计中信银行支付订单>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_OrderCitic_Select] 
@transdate datetime,
@totalTrsCnt int output,--订单数
@traSumAmt decimal(18,2) output--订单总额
AS
BEGIN
select @transdate=isnull(@transdate,getdate())
select o.orderno,r.[money]
into #o
from orders o(nolock),payment p(nolock),receivepay r(nolock) 
where o.orderno=r.orderno and o.paymenttype=p.paymentid and p.interfaceid=36 and datediff(dd,@transdate,getdate())=0

select @totalTrsCnt=count(*),@traSumAmt=sum(money) from #o
--insert into log(content) values(convert(varchar(20),@totalTrsCnt)+'|'+convert(varchar(20),@traSumAmt))
select * from #o
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderInvoice_Insert]    脚本日期: 04/09/2012 18:27:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas>
-- Create date: <2011-03-12>
-- Description:	<记录订单发票信息>
/*
引用该存储过程的存储过程：
1、XpProc_Order_Make
*/
-- =============================================
CREATE PROC [dbo].[XpProc_OrderInvoice_Insert]
	@OrderID int,
	@InvoiceType int,
	@InvoiceHead nvarchar(50),
	@IsDetails tinyint,
	@InvoiceContent nvarchar(300)='明细',
	@MemberID int
AS
--如果发票内容为明细，则InvoiceContent赋值为'明细'
if @IsDetails=1
select @InvoiceContent='明细'

INSERT orderinvoice(OrderID, InvoiceType, InvoiceHead, IsDetails, InvoiceContent,MemberID)
VALUES (@OrderID, @InvoiceType, @InvoiceHead, @IsDetails, @InvoiceContent,@MemberID)

RETURN SCOPE_IDENTITY()

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderList_Get]    脚本日期: 04/09/2012 18:27:37 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE procedure [dbo].[XpProc_OrderList_Get]
(
@pagerows int,        --每页行数    
@pageindex int,        --索引
@total nvarchar(4000),    --条件
@rows int output,--总行数
@pageSize int=null output, --每一页的页的大小
@pageQuantity int=null output,--当前页的商品数量
@pageTotalPrice decimal(18,2) =null output --当前页的商品的总价
)
as
begin
set nocount on
declare 
@befrows int,
@sql nvarchar(4000)
set @befrows=@pagerows*(@pageindex-1)

--每页的订单列表数据
set @sql='select op.orderid,op.orderno,thumbnailimg,productname,unitprice,op.quantity,Totalprice,
receivername,receiverphone,receiverMobile,receiveraddress,shiptime,op.ordertime ,paytime ,status,paytype,productid
from orderproduct(nolock)op,orders(nolock) o 
where op.orderid=o.orderid and o.orderid in '+
'(select orderid from (select top '+cast(@pagerows as nvarchar(50))+' orderid  from orders 
where '+@total+' and orderid not in 
(select top '+cast(@befrows as nvarchar(50))+' orderid from orders where '+@total+' order by orderid desc )
order by orderid desc )a)'
create table #table(orderid int,orderno nvarchar(50),thumbnailimg nvarchar(100),productname nvarchar(500),unitprice decimal(18,2),
quantity int,totalprice decimal(18,2),receivername nvarchar(255),receiverphone nvarchar(255),receivermobile varchar(20),
receiveraddress nvarchar(255),shiptime nvarchar(50),ordertime datetime,paytime datetime,status int,paytype int,productid int)
insert into #table exec (@sql)
select * from #table

--每页的pageSize,每页包含的商品的数量
select @pageSize=count(*),@pageQuantity=sum(quantity)from #table
--每页商品的总价
select distinct(orderid),totalprice into #temp from #table
select @pageTotalPrice=sum(totalPrice)from #temp

---------总条数------
set @sql=N'select @rows=count(*) from orders where '+@total+'  '+''

exec sp_executesql @sql,N'@rows int out',@rows out
select  @rows
return @rows
end


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderMoney_Change]    脚本日期: 04/09/2012 18:27:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-11-11>
-- Description:	<调整订单金额和运费>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_OrderMoney_Change] 
@orderid int,--订单ID
@adminid int,--管理员ID
@adminname varchar(20),--管理员姓名
@dprice decimal(18,2),--优惠金额
@shipprice decimal(18,2),--运费
@remark varchar(200),--操作描述
@errorflag int output,--错误标志
@errormsg varchar(200) output --错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''
Begin Try
declare @orderno varchar(20),@oldordermoney decimal(18,2),@oldshipprice decimal(18,2),@newordermoney decimal(18,2),@status int,@opdesc varchar(200)
select @orderno=''
select @orderno=orderno,@oldordermoney=totalprice,@oldshipprice=shipprice,@status=status from orders(nolock) where orderid=@orderid
select @newordermoney=@oldordermoney+@dprice+(@shipprice-@oldshipprice)

--订单判断
if @orderno=''
begin
select @errorflag=1,@errormsg='不存在该订单'
return
end 

--金额判断
if @newordermoney<0
begin
select @errorflag=1,@errormsg='优惠金额不能大于订单总额'
return
end 

if @status<2 --未付款的订单才可以修改价格
begin
begin tran
update orders set totalprice=@newordermoney,needpaymoney=isnull(needpaymoney,0)+@dprice+@shipprice-@oldshipprice,shipprice=@shipprice where orderid=@orderid
if isnull(@remark,'')=''
select @remark='修改订单金额'

select @opdesc=@remark+'（修改前订单金额：'+cast(@oldordermoney as varchar(20))+',运费：'+cast(@oldshipprice as varchar(20))+'；修改后订单金额：'+cast(@newordermoney as varchar(20))+',运费：'+cast(@shipprice as varchar(20))+')'
exec XpProc_OrderOpLog_Add @orderid,@orderno,@adminname,@adminid,'管理员',@opdesc,@remark,@status,1
commit
end
else
begin
select @errorflag=1,@errormsg='不能修改已付款订单的金额'
end
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderOpLog_Add]    脚本日期: 04/09/2012 18:27:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2010-05-30>
-- Description:	<记录对订单的操作>
-- =============================================
CREATE PROC [dbo].[XpProc_OrderOpLog_Add]
@OrderID int=null,--订单ID
@OrderNo varchar(50)=null,--订单编号
@OPName varchar(20) = NULL,--操作员的名称
@operator int=Null,--操作员的会员ID
@OPRule varchar(50) = NULL,--操作角色 顾客，系统，商家,管理员
@OPDesc varchar(200) = NULL,--操作描述
@OPRemark varchar(200) =NULL,--操作备注
@OPStatus int,--更改订单的状态
@Status int--状态
--	@PreStatus int = NULL,
--	@PreStatusInfo varchar(20) = NULL,
--	@OPStatusInfo varchar(20) = NULL

AS
begin
declare @PreStatus int --操作前的订单状态
declare @PreStatusInfo varchar(20) --操作前订单状态描述
declare @OPStatusInfo varchar(20) --操作后订单状态描述
declare @memberid int --订单所属会员ID
declare @paytype int --支付类型，主要分为二种，款到发货与货到付款
--declare @orderno varchar(50) --订单编号
--declare @name nvarchar(200)--会员名
--declare @OPRule varchar(50) --操作角色 顾客，系统，商家
--declare @opDesc varchar(200) --操作描述

if @OrderNo is null
begin
select @PreStatus=status ,@orderno=orderno ,@paytype=paytype,@memberid=memberid 
from orders(nolock)
where orderid=@OrderID
end
else
begin
select @PreStatus=status ,@OrderID=orderid ,@paytype=paytype,@memberid=memberid 
from orders(nolock)
where orderno=@OrderNo
end

--刚生成的订单写日志要把前一订单状态置为-1
if @OPStatus=0
begin
select @PreStatus=-1
end

--定义OrderOpLog表中用到的一些字段的默认值
if (@paytype<=4) --这个款到发货的
begin
	select @PreStatusInfo= --设置对操作前的订单状态的描述
	case @PreStatus
		WHEN -1 Then '----'
		WHEN 0 Then '未付款'
		WHEN 1 THEN '部分付款'
		WHEN 2 THEN '已付款'
		WHEN 3 THEN '已确认'
		WHEN 4 THEN '正在配货'
		WHEN 5 THEN '已部分发货'
		WHEN 6 THEN '已发货'
		WHEN 7 THEN '已签收'
		WHEN 8 THEN '等待退款'
		WHEN 9 THEN '已退款'
		WHEN 10 THEN '交易取消'
		WHEN 11 THEN '交易失败'
		WHEN 12 THEN '交易完成'
	end
	select @OPStatusInfo= --设置对操作后订单状态的描述
	case @OPStatus
		WHEN -1 THEN @PreStatusInfo
		WHEN 0 Then '未付款'
		WHEN 1 THEN '部分付款'
		WHEN 2 THEN '已付款'
		WHEN 3 THEN '已确认'
		WHEN 4 THEN '正在配货'
		WHEN 5 THEN '已部分发货'
		WHEN 6 THEN '已发货'
		WHEN 7 THEN '已签收'
		WHEN 8 THEN '等待退款'
		WHEN 9 THEN '已退款'
		WHEN 10 THEN '交易取消'
		WHEN 11 THEN '交易失败'
		WHEN 12 THEN '交易完成'
	end
end
else --这个是货到付款
begin
	select @PreStatusInfo= --设置对操作前的订单状态的描述
	case @PreStatus
        WHEN 0 THEN '未确认'
        WHEN 1 THEN '未确认'
        WHEN 2 THEN '未确认'
        WHEN 3 THEN '已确认'
        WHEN 4 THEN '正在配货'
        WHEN 5 THEN '部分发货'
        WHEN 6 THEN '已发货'
        WHEN 7 THEN '已签收'
		WHEN 8 THEN '等待退款'
		WHEN 9 THEN '已退款'
		WHEN 10 THEN '交易取消'
		WHEN 11 THEN '交易失败'
		WHEN 12 THEN '交易完成'
	end
	select @OpStatusInfo= --设置对操作后订单状态的描述
	case @OPStatus
		WHEN -1 THEN @PreStatusInfo
        WHEN 0 THEN '未确认'
        WHEN 1 THEN '未确认'
        WHEN 2 THEN '未确认'
        WHEN 3 THEN '已确认'
        WHEN 4 THEN '正在配货'
        WHEN 5 THEN '部分发货'
        WHEN 6 THEN '已发货'
        WHEN 7 THEN '已签收'
		WHEN 8 THEN '等待退款'
		WHEN 9 THEN '已退款'
		WHEN 10 THEN '交易取消'
		WHEN 11 THEN '交易失败'
		WHEN 12 THEN '交易完成'
	end
end
INSERT orderoplog(OrderID, OrderNo, PreStatus, PreStatusInfo, OPStatus, OPStatusInfo, Operator, OPName,  OPRule, OPDesc, OPRemark, Status)
VALUES (@OrderID, @OrderNo, @PreStatus, @PreStatusInfo, @OPStatus, @OPStatusInfo, @Operator, @OPName, @OPRule, @OPDesc, @OPRemark, COALESCE(@Status, (1)))
end






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderPayNotify_Add]    脚本日期: 04/09/2012 18:27:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO




-- =============================================
-- Author:		<Hakkas@qq.com>
-- Create date: <2011-06-14>
-- Description:	<订单付款通知>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_OrderPayNotify_Add]
	@orderNo varchar(50),--订单编号
	@buyName varchar(50),--付款人姓名
	@payBank varchar(50),--付款银行
	@payAccount varchar(50),--付款账号
	@sellerBank varchar(50)=NULL,--收款银行
	@sellerAccount varchar(50)=NULL,--收款账号
	@workPeople varchar(50),--操作人
	@payTime datetime=NULL,--付款时间
	@payMethod int,--支付类型
	@paymentName varchar(50),--支付方式
	@money decimal(18,2)=NULL,--付款金额
	@outTradeNo varchar(50)=NULL, --外部交易号
	@status int,
	@remark varchar(255)=NULL,--备注
	@OPRule varchar(50),--操作角色 顾客，系统，商家,管理员
	@errorFlag int output
AS
BEGIN
select @errorFlag=1
begin try
	begin tran
	declare @paytype int,@prestatus int,@totalprice decimal(18,2),@needpaymoney decimal(18,2),@supplierid int ,@orderid int,@ProductPrice decimal(18,2),@ordertime datetime
	select @totalprice=totalprice,@needpaymoney=needpaymoney,@paytype=paytype,@prestatus=status,@supplierid=supplierid,@orderid=orderid ,@ProductPrice=ProductPrice,@ordertime=ordertime 
	from orders(nolock) 
	where OrderNo=@orderno
	--select @paymentname=p.[name],@money=o.totalprice from Payment p(nolock),Orders o(nolock) where o.PaymentType = p.PaymentID and o.OrderNo=@orderno

	if @paytype<>5 and @paytype<>6--非货到付款订单
	begin
	print('还未付款的订单才需要写财务记录及更改订单状态为已付款')
	if @prestatus < 2
	begin
	--插入收款纪录
	INSERT ReceivePay(
	OrderNo, Bank, BankAccount, PayerName, [Money], PayMethod,PaymentName, WorkPeople,  --1
	PayTime, Status, Remark, IsReceive,OutTradeNo, PayBank, PayBankAccount)--2
	VALUES (
	@OrderNo, @sellerBank, @sellerAccount, @buyName, @money, @payMethod,@paymentname, @workPeople, --1
	@payTime,COALESCE(@Status, (1)), @remark, 1, @outTradeNo, @payBank, @payAccount)--2

	--添加订单操作日志
	--exec XpProc_OrderOpLog_Add @orderid,@orderno,@workpeople,@operater,@oprule,@opdesc,@OPRemark,@OPStatus,@Status
	declare @opdesc varchar(50)
	if isnull(@outTradeNo,'')<>''
	select @opdesc='顾客已付款（外部交易号:'+@outTradeNo+'）'
	else 
	select @opdesc='顾客已付款'

	exec XpProc_OrderOpLog_Add null,@orderno,@workPeople,null,@OPRule,@opdesc,'顾客已付款',2,1

	--如果订单状态为未付款的更改订单状态为部分付款或已付款 ，一个订单多次付款会有问题？？？
	if @money<@needpaymoney
		begin
			--更改订单为部分付款
			update orders set needpaymoney=@needpaymoney-@money,status=1,paytime=@payTime where orderno=@orderNo and status=0
		end
	else
		begin
			--更改订单状态为已付款
			update orders set needpaymoney=0,status=2,paytime=@payTime where orderno=@orderNo and status<2
		end

	--在线支付送礼品
	exec XpProc_PayOnLineGift_Send @orderno,@money,null

	--插入财务明细表
	declare @yongjin money,@bprate float
	select @bprate=BPRate from supplier where supplierid=@supplierid
	select @yongjin = round(@ProductPrice*@bprate,2)
	exec XpProc_FinanceDetail_Insert @ordertime,@orderid,@orderno,@totalPrice,0,@yongjin,@supplierid,0

	--插入推广员的提成金额
	exec XpProc_AgentFinance_Add @orderid

	end
	end
	else--货到付款订单
	begin
	--插入收款纪录
	INSERT ReceivePay(
	OrderNo, Bank, BankAccount, PayerName, [Money], PayMethod,PaymentName, WorkPeople,  --1
	PayTime, Status, Remark, IsReceive,OutTradeNo, PayBank, PayBankAccount)--2
	VALUES (
	@OrderNo, @sellerBank, @sellerAccount, @buyName, @money, @payMethod,@paymentname, @workPeople, --1
	@payTime,COALESCE(@Status, (1)), @remark, 1, @outTradeNo, @payBank, @payAccount)--2
	if @prestatus=6
	begin
	--如果订单状态为已发货的更改订单状态为已签收
	--exec XpProc_OrderOpLog_Add @orderid,@orderno,@workpeople,@operater,@oprule,@opdesc,@OPRemark,@OPStatus,@Status
	exec XpProc_OrderOpLog_Add null,@orderno,@workPeople,null,@OPRule,'顾客已签收','顾客已签收',2,1
	update orders set needpaymoney=0,status=7,paytime=@payTime where orderno=@orderNo and status=6
	end
	end
	select @errorFlag=0
	commit tran
end try
begin catch
	select @errorflag=1
	rollback tran
end catch
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderProduct_Get]    脚本日期: 04/09/2012 18:27:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-09-05>
-- Description:	<会员中心,根据订单号查找要退换货/返修的订单商品>
-- Debug:
/*
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_OrderProduct_Get]
@memberid int=null, --会员ID
@type int =null,--会员的申请类型，1退货，2换货3返修
@name varchar(200)=null,--用户名
@orderno varchar(50),--订单编号
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
if(@memberid is null)
select @memberid=memberid from member(nolock) where name=@name


--orders表中的servicestatus的状态
--1	客户申请退货
--2	退货中
--3	退款中
--4退款成功
--5	申请关闭(退货)				
--6客户申请换货
--7换货中	
--8换货完成
--9申请关闭(换货)
--10客户申请返修
--11返修中
--12返修成功
--13申请关闭(返修)
--14 客户申请退款
--15 退款中
--16退款完成
--17申请关闭(直接退款)

--appoplog日志的status状态
--0 未审核
--1 审核已过
--2 审核未过
--3 客户寄回要处理的商品
--4 不同意退换返修
--5 同意换货返修
--6 同意退货
--7 商家寄回未处理的商品
--8 客户签收未处理的商品
--9 商家寄回收处理后的商品
--10 客户签收处理后的商品
--11 退款中
--12 已退款
--测试订单所在的状态是否满足客户的申请，不满足则退出且给出提示信息


if @type=1 --申请退货
begin
select * into #t1 from orders where orderno=@orderno and memberid=@memberid 
if not exists( select orderid from #t1)
begin
select @errorflag=1
select @errorMsg='订单不存在，不可提交退货申请!'
return
end
if exists (select orderid from #t1 where status<7)
begin
select @errorflag=1
select @errorMsg='订单还未签收，不可提交退货申请!'
return
end
if exists (select orderid from #t1 where status in(7,12) and datediff(day,receivetime,getDate())>7)
begin
select @errorflag=1
select @errorMsg='您好，货物签收已超过7天，不可提交退货申请!'
return
end
if exists (select orderid from #t1 where status not in(7,12))
begin
select @errorflag=1
select @errorMsg='您好，订单不是签收或完成状态，不可提交退货申请'
return
end
if exists (select orderid from #t1 where servicestatus in(1,2,3))
begin
select @errorflag=1
select @errorMsg='您好，此订单正在退货中，不可再提交退货申请！'
return
end
if exists (select orderid from #t1 where servicestatus=4)
begin
select @errorflag=1
select @errorMsg='您好，此订单已完成退货，不可再提交退货申请！'
return
end
if exists (select orderid from #t1 where servicestatus=5)
begin
select @errorflag=1
select @errorMsg='您好，此订单已退货申请已关闭，不可再提交退货申请！'
return
end
end
else if @type=2  --换货
begin
select * into #t2 from orders where orderno=@orderno and memberid=@memberid 
if not exists( select orderid from #t2)
begin
select @errorflag=1
select @errorMsg='订单不存在，不可提交换货申请!'
return
end
if exists (select orderid from #t2 where status<7)
begin
select @errorflag=1
select @errorMsg='订单还未签收，不可提交换货申请!'
return
end
if exists (select orderid from #t2 where status in(7,12) and datediff(day,receivetime,getDate())>30)
begin
select @errorflag=1
select @errorMsg='您好，货物签收已超过30天，不可提交换货申请!'
return
end
if exists (select orderid from #t2 where status not in(7,12))
begin
select @errorflag=1
select @errorMsg='您好，订单不是签收或完成状态，不可提交换货申请!'
return
end
if exists (select orderid from #t2 where servicestatus in(6,7))
begin
select @errorflag=1
select @errorMsg='您好，此订单正在换货中，不可再提交换货申请!'
return
end
--if exists (select orderid from #t2 where servicestatus=8)
--begin
--select @errorflag=1
--select @errorMsg='您好，此订单已完成换货，不可再提交换货申请!'
--return
--end
if exists (select orderid from #t2 where servicestatus=9)
begin
select @errorflag=1
select @errorMsg='您好，此订单换货申请已关闭，不可再提交换货申请!'
return
end
end
else if @type=3  --返修
begin
select * into #t3 from orders where orderno=@orderno and memberid=@memberid 
if not exists( select orderid from #t3)
begin
select @errorflag=1
select @errorMsg='订单不存在，不可提交返修申请!'
return
end
if exists (select orderid from #t3 where status<7)
begin
select @errorflag=1
select @errorMsg='订单还未签收，不可提交返修申请!'
return
end
if exists (select orderid from #t3 where status in(7,12) and datediff(day,receivetime,getDate())>365)
begin
select @errorflag=1
select @errorMsg='您好，货物签收已超过365天，不可提交返修申请!'
return
end
if exists (select orderid from #t3 where status not in(7,12))
begin
select @errorflag=1
select @errorMsg='您好，订单不是签收或完成状态，不可提交返修申请!'
return
end
if exists (select orderid from #t3 where servicestatus in(10,11))
begin
select @errorflag=1
select @errorMsg='您好，此订单正在换货中，不可再提交返修申请!'
return
end
--if exists (select orderid from #t3 where servicestatus=12)
--begin
--select @errorflag=1
--select @errorMsg='您好，此订单已完成返修，不可再提交返修申请!'
--return
--end
if exists (select orderid from #t3 where servicestatus=13)
begin
select @errorflag=1
select @errorMsg='您好，此订单返修申请已关闭，不可再提交返修申请!'
return
end
end

select op.orderID,op.orderNo,op.ProductName,op.GoodsID,ProductSpecs,SubPrice,UnitPrice,cast((op.LessMoney/op.Quantity)as decimal(18,2))as UnitLess,op.Quantity,op.LessMoney,Ptype,GiftGetType,Status,ReceiverAddress,ReceiverMobile,ReceiverName,o.MemberID into #t
from orderproduct(nolock) op,orders(nolock) o 
--where (o.status=7 or o.status=12) and op.orderid=o.orderid and op.orderno=@orderno and op.memberid=@memberid AND Ptype = 1 and GiftGetType =0
where op.orderid=o.orderid and op.orderno=@orderno and op.memberid=@memberid AND Ptype = 1 and GiftGetType =0
select @errorflag=0,@errormsg=''
select *from #t
--declare @total int --符合条件的纪录数
--select @total=count(*) from #t
--if(@total=0)
--begin
--	if exists(select productname from orderproduct(nolock) where orderno=@orderno and memberid=@memberid)
--	select @errorflag=0,@errormsg='你的这个订单不能退换货或返修'
--	else
--	select @errorflag=1,@errormsg='订单不存在'
--end
end




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderRefundNotify_Add]    脚本日期: 04/09/2012 18:27:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Hakkas@qq.com>
-- Create date: <2011-06-14>
-- Description:	<退款通知>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_OrderRefundNotify_Add]
	@orderNo varchar(50),--订单编号
	@buyName varchar(50),--付款人姓名
	@payBank varchar(50),--付款银行
	@payAccount varchar(50),--付款账号
	@sellerBank varchar(50)=NULL,--收款银行
	@sellerAccount varchar(50)=NULL,--收款账号
	@workPeople varchar(50),--操作人
	@payTime datetime=NULL,--退款时间
	@payMethod int,--支付类型
	@paymentName varchar(50),--支付方式
	@money decimal(18,2)=NULL,--退款金额
	@outTradeNo varchar(50)=NULL, --外部交易号
	@status int,
	@remark varchar(255)=NULL,--备注
	@errorFlag int output
AS
BEGIN
select errorFlag=1
begin tran
declare @paytype int
select @paytype=paytype from orders where OrderNo=@orderno

--插入收退款纪录
INSERT ReceivePay(
OrderNo, Bank, BankAccount, PayerName, [Money], PayMethod,PaymentName, WorkPeople,  --1
PayTime, Status, Remark, IsReceive,OutTradeNo, PayBank, PayBankAccount)--2
VALUES (
@OrderNo, @sellerBank, @sellerAccount, @buyName, @money, @payMethod,@paymentname, @workPeople, --1
@payTime,COALESCE(@Status, (1)), @remark, 0, @outTradeNo, @payBank, @payAccount)--2

--更改订单状态为已退款
update orders set status=9,paytime=@payTime where orderno=@orderNo
select @errorFlag=0
commit tran
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderRelateInfo_Get]    脚本日期: 04/09/2012 18:27:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-06-01>
-- Description:	<用于会员中心，商家后台查看订单，管理后台打印订单>
-- =============================================
CREATE PROC [dbo].[XpProc_OrderRelateInfo_Get]
	@orderid int,
	@id int,--会员ID，商家ID
	@flag int ,--用于标记是在会员中心还是商家后台,还是管理员后台查看订单，0表示会员中心查看，1商家后台查看，2管理后台打印订单，3管理后台查看
	@errorFlag int=1 output, --0表示这个订单属于这个会员的，可以查看订单，否则为1
	@errorMsg varchar(200)=null output
AS
begin
	select @errorFlag=1
	if(@flag=0)--会员中心查看订单
	begin
		declare @mid int
		select @mid=memberid from orders(nolock)where orderid=@orderid
		--订单不存在或者这个订单不是这个会员的
		if(@mid is null or @mid<>@id)
		begin
			set @errorFlag=1
			set @errorMsg='不是这个会员的订单'
		end
		else
		begin
		--table[0]订单信息
		SELECT Orders.OrderID,Orders.MemberID,OrderTime,ShipTime,BuyerName,BuyerPhone,BuyerMobile,BuyerEmail,BuyerAddress,BuyerPostalcode,
		Orders.ReceiverName,ReceiverPhone,ReceiverEmail,ReceiverAddress,ReceiverPostalcode,Orders.Remark,TotalPrice,Orders.NeedPayMoney,Orders.LessMoney,Orders.CouponValue,ProductPrice,
		CustomItemPrice,Discount,ShipPrice,AdvancePayment,PaymentType,ShippingType,Score,Weight,Orders.Quantity,NeedInvoice,TaxPrice,
		CltCharge,Orders.PayType,Orders.Status,ManageHistory,LastModify,Orders.OrderNo,Code,IsAgentF,IsAgentFContent,IsShippingFree,
		Type,Favourable,ZtdNo,IsToErp,OrderType,IsToMessage,AddMethod,UsedScore,ScoreAmount,Shipping.[Name] as ShippingName,Shipping.QueryUrl,
		PayNotify.PayNotifyID,ShippingInvoice.ShippingInvoiceID,ShippingInvoice.ShipCompanyName,ShippingInvoice.ShippingNo,
		case orders.paytype when 1 then paytypename+ isnull('('+payment.name+')','') else paytypename end as PayMentName,ReceiverMobile
		FROM Orders(nolock)
		left join Shipping(nolock) on Orders.ShippingType = Shipping.ShippingID 
		left join PayNotify(nolock) on Orders.orderID = PayNotify.OrderID
		left join ShippingInvoice(nolock) on Orders.orderID = ShippingInvoice.OrderID
		left join payment on payment.paymentid=orders.paymenttype
		left join paytype on orders.paytype=paytype.paytypeid
		WHERE Orders.OrderID =@orderid

		--table[1]取得发票详情
		SELECT OrderInvoiceID,OrderID,InvoiceType,InvoiceHead,IsDetails,InvoiceContent 
		FROM OrderInvoice(nolock)
		WHERE OrderID =@orderid
		
		--table[2]绑定商品
		select OrderID,ProductNo,ProductID,ProductName,Remark,OrderProductID,GoodsID,LessMoney,Quantity,UnitPrice,Score,CommentStatus 
		into #temp0
		from OrderProduct(nolock) 
		where 
		orderid=@orderid and Ptype =1 --and GiftGetType = 0 
		select * from #temp0
		--table[3]绑定的礼品
		select giftname,quantity,giftscore,(quantity*giftscore) as total
		from gift g,orderproduct op where orderid=@orderid and Ptype =2 and (GiftGetType = 1 or GiftGetType=2) and g.productid=op.productid
--		select ProductName,Quantity,GiftScore,Quantity from OrderProduct(nolock) where orderid=@orderid and Ptype =2 and (GiftGetType = 1 or GiftGetType=2) ORDER BY OrderID DESC
		--table[4]绑定订单操作记录
		select OpRule,OPTime,OPDesc 
		from OrderOpLog(nolock) 
		where orderid=@orderid 
		ORDER BY  OPTime asc,id desc
		--table[5]订单是否可以合并
		select count(OrderID)as total 
		from Orders 
		where OrderID =@orderid and (Orders.Status = 0 or (Orders.Status = 2 and PayType IN(5,6))) 
		--table[6]绑定某个商品的赠品
		select orderpresent.productID,presentName,PresentNum 
		from OrderPresent(nolock),#temp0 
		where OrderPresent.OrderID =@orderid and OrderPresent.ProductID = #temp0.productID 
		order by Ptype
		--table[7]绑定优惠券
		select isnull(productid,-1) as productid,CouponName,couponvalue,number,subnumber,sendreason,case when status=1 then '(已发放)' else '(订单完成后自动发放)' end as status from ordercoupon c(nolock) where c.orderid=@orderid and status>-1
		set @errorFlag=0
		end
	end

	--商家后台查看订单开始
	else if(@flag=1)
	begin
		declare @sid int
		select @sid=supplierid from orders(nolock)where orderid=@orderid
		--订单不存在或者这个订单不是这个商家的
		if(@sid is null or @sid<>@id)
		begin
			set @errorFlag=1
			set @errorMsg='不是这个商家的订单'
		end
		else
		begin
		--table[0]订单信息
		SELECT Orders.OrderID,Orders.MemberID,OrderTime,ShipTime,BuyerName,BuyerPhone,BuyerMobile,BuyerEmail,BuyerAddress,BuyerPostalcode,
		Orders.ReceiverName,ReceiverPhone,ReceiverEmail,ReceiverAddress,ReceiverPostalcode,Orders.Remark,TotalPrice,Orders.NeedPayMoney,Orders.LessMoney,Orders.CouponValue,ProductPrice,
		CustomItemPrice,Discount,ShipPrice,AdvancePayment,PaymentType,ShippingType,Score,Weight,Orders.Quantity,NeedInvoice,TaxPrice,
		CltCharge,Orders.PayType,Orders.Status,ManageHistory,LastModify,Orders.OrderNo,Code,IsAgentF,IsAgentFContent,IsShippingFree,
		Type,Favourable,ZtdNo,IsToErp,OrderType,IsToMessage,AddMethod,UsedScore,ScoreAmount,Shipping.[Name] as ShippingName,Shipping.QueryUrl,
		PayNotify.PayNotifyID,ShippingInvoice.ShippingInvoiceID,ShippingInvoice.ShipCompanyName,ShippingInvoice.ShippingNo,
		case orders.paytype when 1 then paytypename+ isnull('('+payment.name+')','') else paytypename end as PayMentName,ReceiverMobile 
		FROM Orders(nolock)
		left join Shipping(nolock) on Orders.ShippingType = Shipping.ShippingID left join PayNotify(nolock) on Orders.orderID = PayNotify.OrderID
		left join ShippingInvoice(nolock) on Orders.orderID = ShippingInvoice.OrderID
		left join payment on payment.paymentid=orders.paymenttype
		left join paytype on orders.paytype=paytype.paytypeid
		WHERE Orders.OrderID =@orderid
		--table[1]取得发票详情
		SELECT OrderInvoiceID,OrderID,InvoiceType,InvoiceHead,IsDetails,InvoiceContent 
		FROM OrderInvoice(nolock) 
		WHERE OrderID =@orderid
		--table[2]绑定商品
		select OrderID,ProductNo,ProductID,ProductName,Remark,OrderProductID,GoodsID,LessMoney,Quantity,UnitPrice,Score,CommentStatus 
		from OrderProduct(nolock)
		where orderid=@orderid and Ptype =1 --and GiftGetType = 0
		ORDER BY OrderID DESC

		--table[3]绑定的礼品
		select * 
		from OrderProduct(nolock) where orderid=@orderid and Ptype =2 and (GiftGetType = 1 or GiftGetType=2)
		ORDER BY OrderID DESC
		--table[4]绑定订单操作记录
		select OpRule,OPTime,OPDesc 
		from OrderOpLog(nolock) 
		where orderid=@orderid 
		ORDER BY  OPTime asc,id desc

		--以下用于商家发货
		--table[5]
		select productname,productno,productid,orderproduct.quantity,Stockout,goodsid,unitprice,subprice ,totalprice,productprice,shipprice ,advancepayment, --一个订单里还需要发货的商品
		orders.score,orders.quantity,paytype,status,favourable,ordertype,orders.usedscore
		from orderproduct(nolock), orders(nolock) 
		where orderproduct.orderid=orders.orderid and orderproduct.orderid=@orderid and Ptype =1 and GiftGetType = 0 and stockout>0
		--table[6]
		select * from Express(nolock) 
		where supplierid=@sid 
		order by Isuseful desc,sort --商家设定的快递公司
		
		--table[7]绑定优惠券
		select isnull(productid,-1) as productid,couponname,couponvalue,number,subnumber,sendreason,case when status=1 then '(已发放)' else '(订单完成后自动发放)' end as Status from ordercoupon c(nolock) where c.orderid=@orderid and status>-1

		set @errorFlag=0
		end
	end

	--管理后台打印订单开始
	else if(@flag=2)
	begin
		--table[0]订单信息
		SELECT Orders.OrderID,Orders.MemberID,OrderTime,ShipTime,BuyerName,BuyerPhone,BuyerMobile,BuyerEmail,BuyerAddress,BuyerPostalcode,
		Orders.ReceiverName,ReceiverPhone,ReceiverEmail,ReceiverAddress,ReceiverPostalcode,Orders.Remark,TotalPrice,Orders.NeedPayMoney,Orders.LessMoney,Orders.CouponValue,ProductPrice,
		CustomItemPrice,Discount,ShipPrice,AdvancePayment,PaymentType,ShippingType,Score,Weight,Orders.Quantity,NeedInvoice,TaxPrice,
		CltCharge,Orders.PayType,Orders.Status,ManageHistory,LastModify,Orders.OrderNo,Code,IsAgentF,IsAgentFContent,IsShippingFree,
		Type,Favourable,ZtdNo,IsToErp,OrderType,IsToMessage,AddMethod,UsedScore,ScoreAmount,Shipping.[Name] as ShippingName,Shipping.QueryUrl,
		PayNotify.PayNotifyID,ShippingInvoice.ShippingInvoiceID,ShippingInvoice.ShipCompanyName,ShippingInvoice.ShippingNo ,orders.quantity ,
		case orders.paytype when 1 then paytypename+ isnull('('+payment.name+')','') else paytypename end as PayMentName,ReceiverMobile
		FROM Orders(nolock)
		left join Shipping(nolock) on Orders.ShippingType = Shipping.ShippingID left join PayNotify(nolock) on Orders.orderID = PayNotify.OrderID
		left join ShippingInvoice(nolock) on Orders.orderID = ShippingInvoice.OrderID 
		left join payment on payment.paymentid=orders.paymenttype
		left join paytype on orders.paytype=paytype.paytypeid
		WHERE Orders.OrderID =@orderid
		--table[1]取得发票详情
		SELECT OrderInvoiceID,OrderID,InvoiceType,InvoiceHead,IsDetails,InvoiceContent FROM OrderInvoice(nolock) WHERE OrderID =@orderid
		--table[2]绑定商品
--		select * from OrderProduct(nolock) where orderid=@orderid and Ptype =1 and GiftGetType = 0 ORDER BY OrderID DESC
		select ProductNo,ProductID,ProductName,OrderProductID,GoodsID,LessMoney,Quantity,UnitPrice,ItemsPrice,IsDiscount,SubPrice into #temp1
		from OrderProduct(nolock) 
		where orderid=@orderid and Ptype =1 --and GiftGetType = 0 
		ORDER BY OrderID DESC
		select * from #temp1
		--table[3]绑定的礼品
		select giftname,quantity,giftscore,(quantity*giftscore) as total
		from gift g,orderproduct op 
		where orderid=@orderid and Ptype =2 and (GiftGetType = 1 or GiftGetType=2) and g.productid=op.productid
		--table[4]绑定订单操作记录
		select OpRule,OPTime,OPDesc 
		from OrderOpLog(nolock) 
		where orderid=@orderid 
		ORDER BY  OPTime asc,id desc
		--table[5]绑定某个商品的赠品
		select orderpresent.productID,presentName,PresentNum 
		from OrderPresent,#temp1 
		where OrderID =@orderid and OrderPresent.ProductID = #temp1.productID 
		order by Ptype
		set @errorFlag=0
	end	

	--管理后台订单管理
	else if(@flag=3)
	begin
		declare @orderNo varchar(50)--订单编号
		select @orderNo=orderNo from orders where orderid=@orderid
		--table[0]订单信息
		SELECT Orders.OrderID,Orders.MemberID,OrderTime,ShipTime,BuyerName,BuyerPhone,BuyerMobile,BuyerEmail,BuyerAddress,BuyerPostalcode,
		Orders.ReceiverName,ReceiverPhone,ReceiverEmail,ReceiverAddress,ReceiverPostalcode,Orders.Remark,TotalPrice,Orders.NeedPayMoney,Orders.LessMoney,Orders.CouponValue,ProductPrice,
		CustomItemPrice,Discount,ShipPrice,AdvancePayment,PaymentType,ShippingType,Score,Weight,Orders.Quantity,NeedInvoice,TaxPrice,
		CltCharge,Orders.PayType,Orders.Status,ManageHistory,LastModify,Orders.OrderNo,Code,IsAgentF,IsAgentFContent,IsShippingFree,
		Type,Favourable,ZtdNo,IsToErp,OrderType,IsToMessage,AddMethod,UsedScore,ScoreAmount,orders.supplierid,Shipping.[Name] as ShippingName,Shipping.QueryUrl,
		PayNotify.PayNotifyID,ShippingInvoice.ShippingInvoiceID,ShippingInvoice.ShipCompanyName,ShippingInvoice.ShippingNo ,orders.quantity ,
		case orders.paytype when 1 then paytypename+ isnull('('+payment.name+')','') else paytypename end as PayMentName,ReceiverMobile
		FROM Orders(nolock)
		left join Shipping(nolock) on Orders.ShippingType = Shipping.ShippingID left join PayNotify(nolock) on Orders.orderID = PayNotify.OrderID
		left join ShippingInvoice(nolock) on Orders.orderID = ShippingInvoice.OrderID 
		left join payment on payment.paymentid=orders.paymenttype
		left join paytype on orders.paytype=paytype.paytypeid
		WHERE Orders.OrderID =@orderid
		--table[1]取得发票详情
		SELECT OrderInvoiceID,OrderID,InvoiceType,InvoiceHead,IsDetails,InvoiceContent 
		FROM OrderInvoice(nolock) 
		WHERE OrderID =@orderid
		--table[2]绑定商品
		select ProductNo,ProductID,ProductName,Remark,OrderProductID,GoodsID,LessMoney,Quantity,UnitPrice,IsDiscount,SubPrice,MemberPrice into #temp3
		from OrderProduct(nolock) 
		where orderid=@orderid and Ptype =1 --and GiftGetType = 0 
		ORDER BY OrderID DESC
		select * from #temp3
		--table[3]绑定的礼品
		select ProductName,Quantity,GiftScore,Quantity 
		from OrderProduct(nolock) where orderid=@orderid and Ptype =2 and (GiftGetType = 1 or GiftGetType=2) 
		ORDER BY OrderID DESC
		--table[4]绑定订单操作记录
		select OpRule,OPTime,OPDesc from OrderOpLog(nolock) where orderid=@orderid ORDER BY  OPTime asc,id desc
		--table[5]支付类型
		select PayTypeName,PayTypeID from PayType(nolock) where Status = 1 order by Sort asc
		--table[6]绑定配送方式
		select [Name],ShippingID from Shipping(nolock)
		--table[7]绑定支付方式
		select [Name],PaymentID from Payment(nolock) where PayType = 1 and Status = 1 Order By Sort Asc
		--table[8]绑定自提点
		SELECT ZtdName,ZtdNo FROM Ztd(nolock) ORDER BY ZtdID
		--table[9]绑定收款单
		SELECT [Money],PaymentName,WorkPeople,AddTime FROM ReceivePay(nolock) WHERE OrderNo=@orderNo AND IsReceive =1 ORDER BY ReceivePayID
		--table[10]绑定退款单
		SELECT [Money],PaymentName,WorkPeople,AddTime FROM ReceivePay(nolock) WHERE OrderNo=@orderNo AND IsReceive =0 ORDER BY ReceivePayID
		--table[11]绑定发货单
		SELECT ShippingNo,ReceiverName,[name]as ShippingName,Admin ,addtime FROM ShippingInvoice(nolock) left join Shipping(nolock) on ShippingInvoice.ShippingID 
		= Shipping.ShippingID WHERE ShippingInvoice.OrderID =@orderID AND ShippingInvoice.IsReturn =0 ORDER BY ShippingInvoice.ShippingInvoiceID
		--table[12]绑定退货单
		SELECT ShippingNo,ReceiverName,[name],Admin FROM ShippingInvoice(nolock) left join Shipping(nolock) on ShippingInvoice.ShippingID 
		= Shipping.ShippingID WHERE ShippingInvoice.OrderID =@orderID AND ShippingInvoice.IsReturn =1 ORDER BY ShippingInvoice.ShippingInvoiceID
		--table[13]绑定回复数
		select OrderReviewID,Body,Reply,Orders.OrderID as OID FROM OrderReview(nolock),Orders(nolock) where OrderReview.OrderID = Orders.OrderID and Orders.OrderID = @orderid
	    ORDER BY  OrderReview.AddTime desc
		--table[14]绑定某个商品的赠品
		select orderpresent.productID,presentName,PresentNum from OrderPresent(nolock),#temp3 where OrderID =@orderid and OrderPresent.ProductID = #temp3.productID order by Ptype

		--填写发货单用到
		--table[15]还需发货的商品
		select productname,productno,productid,orderproduct.quantity,Stockout,goodsid,unitprice,subprice ,totalprice,productprice,shipprice ,advancepayment, --一个订单里还需要发货的商品
		orders.score,orders.quantity,paytype,status,favourable,ordertype,orders.usedscore,productspecs
		from orderproduct(nolock), orders(nolock) where orderproduct.orderid=orders.orderid and orderproduct.orderid=@orderid
--		and Ptype =1 and GiftGetType = 0 
		and stockout>0
		--table[16]商家设定的快递公司
		select Expressname,QueryUrl from Express(nolock) where supplierid=0 order by Isuseful desc,sort 
		
		--填写退款单用到
		--table[17]获取一个订单，商家已收到的金额
		select (
		cast((select isnull(sum([Money]),0) from ReceivePay(nolock) where OrderNo =@orderNo and IsReceive = 1)-
		(select isnull(sum([Money]),0) from ReceivePay(nolock) where OrderNo =@orderNo and IsReceive = 0) as decimal(18,2))
		) as paid
		--table[18]绑定支付方式
		SELECT * FROM Payment(nolock) ORDER BY PaymentID
		--table[19]顾客付款的银行
--		select'['+Bank+']['+BankAccount+']' as Bank,BankAccount from ReceivePay where ReceivePayID in (select max(ReceivePayID) from ReceivePay where BankAccount != '' group by BankAccount)
		select Bank,BankAccount from ReceivePay where ReceivePayID in (select max(ReceivePayID) from ReceivePay where BankAccount != '' group by BankAccount)
		--table[20]运营商用于退款的银行
--		select '['+PayBank+']['+PayBankAccount+']' as PayBank,PayBankAccount from ReceivePay where ReceivePayID in (select max(ReceivePayID) from ReceivePay where PayBankAccount != '' group by PayBankAccount)
		select PayBank,PayBankAccount from ReceivePay where ReceivePayID in (select max(ReceivePayID) from ReceivePay where PayBankAccount != '' group by PayBankAccount)

		--table[21]绑定优惠券
		select isnull(productid,-1) as productid,couponname,couponvalue,number,subnumber,sendreason,case when status=1 then '(已发放)' else '(订单完成后自动发放)' end as status from ordercoupon c(nolock) where c.orderid=@orderid and status>-1
		set @errorFlag=0
	end
end


--测试用
--declare @errorflag int
--declare @errorMsg varchar(200)
--exec XpProc_OrderRelateInfo_Get 150,'',3,@errorflag output,@errormsg
--select @errorflag,@errormsg












GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderRemark_Update]    脚本日期: 04/09/2012 18:27:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2012-01-17>
-- Description:	<修改Orders表中的某个字段的值，并加入订单日志>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_OrderRemark_Update]
@orderID int=null,--订单ID
@operator int =null,--操作人ID
@opname varchar(20)=null,--操作人真实姓名
@OPRule varchar(50)=null,--操作角色 顾客，系统，商家,管理员
@remark varchar(200)=null,--新的订单附言
@ip varchar(40)=null,--ip
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
declare @newremark varchar(max),@orderno varchar(20),@oldremark varchar(max),@opstatus int,@status int
select @orderno=''
select @orderno=orderno,@status=status,@opstatus=@status,@oldremark=remark from orders(nolock) where orderid=@orderid
begin try
begin tran
if(@oldremark<>@remark)
begin
update orders set remark=@remark where orderid=@orderid
declare @opdesc varchar(200)
select @opdesc='订单附言'+case when @oldremark=''then'' else '修改前：'+@oldremark+' ；' end+'修改后：'+@remark
exec XpProc_OrderOpLog_Add @orderid,null,@opname,@operator,'管理员',@opdesc,'',@status,@status
end
select @errorflag=0
select @errormsg='修改订单附言成功！'
commit tran
end try
begin catch
-- 捕捉错误
rollback tran
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
end catch
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Orders_Search]    脚本日期: 04/09/2012 18:27:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[XpProc_Orders_Search] 
(@OrderDateType varchar(8),
@StartTime datetime,
@EndTime datetime
)
AS
set nocount on 
begin
    declare @TempOrder table(totalprice decimal ,ordertime varchar(20))
	--按年来统计销售情况
	if(@OrderDateType='year')
	begin
		insert into @TempOrder select totalprice ,CONVERT(varchar(4), ordertime, 102)as ordertime  from orders where  ordertime between @StartTime and @EndTime
		select count(*)as ordercount,sum(totalprice) as totalprice,ordertime from @TempOrder group by ordertime
	end
	--按月来统计销售情况
	else if(@OrderDateType='month')
	begin
		insert into @TempOrder select totalprice ,CONVERT(varchar(7), ordertime, 102)as ordertime  from orders where  ordertime between @StartTime and @EndTime
		select count(*)as ordercount,sum(totalprice) as totalprice,ordertime from @TempOrder group by ordertime
	end
	--按天来统计销售情况
	else if(@OrderDateType='day')
	begin
		insert into @TempOrder select totalprice ,CONVERT(varchar(11), ordertime, 102)as ordertime  from orders where  ordertime between @StartTime and @EndTime
		select count(*)as ordercount,sum(totalprice) as totalprice,ordertime from @TempOrder group by ordertime
	end
	--在所有的订单中，统计每小时销售情况
	else if(@OrderDateType='hour')
	begin
		insert into @TempOrder select totalprice, CONVERT(varchar(2), ordertime, 114)as ordertime from orders
		select count(*)as ordercount,sum(totalprice) as totalprice,ordertime from @TempOrder group by ordertime
	end

end



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderSecKill_Make]    脚本日期: 04/09/2012 18:27:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-05-20>
-- Description:	<添加秒杀订单>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_OrderSecKill_Make]                 
@cartID nvarchar(36),  --购物车ID  
@memberID int, --会员ID 
@membername nvarchar(100)='',--会员账号
@password varchar(50)='',--密码
@rName nvarchar(20),--收货人姓名
@rEmail nvarchar(20),--收货人EMAIL
@rMobile nvarchar(20),--收货人联系手机
@rPhone nvarchar(20),--收货人联系电话
@rPostalcode nvarchar(20),--收货人邮编
@rAddress  nvarchar(100),--收货人详细地址
@topAreaID int,--省级ID
@subAreaID int,--市级ID
@thirdAreaID int,--县区级ID
@isSaveAddress int,--是否保存收货人地址到地址簿    
@shipAddressID int,--地址簿ID,
@payType int,--支付类型
@shippingID int,--配送方式
@shippingTime nvarchar(50), --送货时间
@code nvarchar(20),--代销人的代销号
@useadvpay tinyint,--是否使用预付款
@needInvoice tinyint,  --是否需要发票    
@invoiceType int,--发票类型
@invoiceHead nvarchar(50),--发票抬头
@isDetails tinyint,--发票内容是否为订单明细
@invoiceContent nvarchar(300),--发票内容
@taxRate decimal(18,2),--税金比例
@remark nvarchar(300),  --Remark 备注                                    
@orderType int,--订单类型:1为正常下订流程的订单,2为团购,3拍卖的订单,4为合并的订单                                                               
@addMethod int,   --AddMethod 下订方式,1是会员在线下的订单,2是管理员代订                                    
@ztdID int,   --取货门店ID   
@ztdNo varchar(20),   --取货门店编号 
@ztdAdminName varchar(100)='',--代下订单管理员账号                              
@ztdAdminID int=null, --代订管理员ID
@addIP varchar(50)='', --下订单人的IP地址
@supplierid int=0,--商家ID    
@errorMsg varchar(200)='' out,--错误信息提示        
@errorFlag int =0 out,--是否错误标识，<>0时，显示错误信息，并返回购物车界面 
@orderID int out, --订单ID
@orderNo nvarchar(30) out,--订单编号
@usedScore int out,--使用的总积分
@scoreSubMoney decimal(18,2) out,--积分抵扣的总金额
@usedAdvPayment decimal(18,2) out,--使用的预付款金额
@pmtPdtPrice decimal(18,2) out,--优惠后商品总价
@totalPrice decimal(18,2) out--订单总价
AS                                           
begin
--设置订单的默认信息 
select @errorMsg='',@errorFlag =1,@orderid=-1,@orderNo='',
@usedScore=0,@scoreSubMoney=0,@usedAdvPayment=0,@pmtPdtPrice=0,@totalPrice=0

Begin Try
print('构造地区ID字符串')
declare @addressID nvarchar(50)--地区ID
select @addressID=cast(@topAreaID as nvarchar(10))+','+cast(@subAreaID as nvarchar(10))+','+cast(@thirdAreaID as nvarchar(10))  
                                
print('新订单的生成..')                               
declare @orlPdtPrice decimal(18,2),--优惠前商品总价
@pmtSubPrice decimal(18,2),--享受的优惠总额
@subscore int,--获得的总积分
@shipPrice decimal(18,2),--配送价格
@taxPrice decimal(18,2),--税率
@weight decimal(18,2),--重量
@cltCharge decimal(18,2),--货到付款手续费
@quantity int,--商品数量
@isAgentF int,
@isShippingFree int,--是否免运费                                   
@sql nvarchar(1000),
@favourable nvarchar(500),--优惠信息
@couponmoney money,--优惠券优惠金额
@membermobile varchar(50),--会员手机号
@memberscore int,--会员当前可使用积分
@groupname nvarchar(20),--会员组名称
@discount nvarchar(20),--会员组折扣
@agentFContent nvarchar(100),
@status int,--订单状态
@ordertime datetime, --下订时间
@advancePayment decimal(18,2), --会员的电子账户余额
@needpaymoney decimal(18,2)--还需支付金额

--初始化变量值
select @isShippingFree=0,@shipPrice=20,@taxPrice=0,@cltCharge=0,@isAgentF=0,@agentFContent='',@favourable='',@status=0,@ordertime=getdate(),@advancePayment=0              

print('获取会员对应会员组享受的折扣')
select @membername=m.[name],@advancePayment=m.AdvancePayment,@memberscore=m.score,@membermobile=m.mobile,@groupname=mg.groupname,@discount=mg.discount 
from member m(nolock),membergroup mg(nolock) 
where m.groupid=mg.MemberGroupID and m.memberid=@memberid

--获取购物车信息
print('商品信息')
select cartid,goodsid,productid,productno,marketprice,memberprice,weight,                                          
pmtprice,quantity,subweight,submoney,lessmoney,                                          
pmtname,ruleid,rulename,basictype,subtype,remark,1 ptype,0 giftscore,0 GiftGetType,convert(nvarchar(20),'goods') PmtType                                         
,g.pmtid ,g.couponID,couponvalue=convert(money,0),coupongoodsmoney=convert(money,0),                                        
CouponMoney=convert(float,0),AvgCouponMoney=convert(float,0),
ProductSpecs,isneedstowage=0,isdiscount,score,0 usescore,ScoreMoney,supplierid,suitid,sort                          
into #cart  
from GoodsCart g(nolock)                                          
where cartid=@cartid 
--and supplierid=@supplierid                                         
and Quantity>0                                          
and addtime>dateadd(hour,-2,getdate())--购物车的商品必须在2小时之内完成。在这里已经存在着限前几名的抢购的问题。                                          
and (isnull(ruleid,0)>0 and addtime>dateadd(minute,-15,getdate()))--促销商品必须在15分钟之内完成。

print('优惠券的使用')                          
select c.couponID--优惠券编号                    
,p.couponvalue,--优惠券值                                       
coupongoodsmoney=sum(isnull(c.pmtprice,c.memberprice)*c.Quantity) --参与优惠券的商品总价                                       
into #couponDetail                                        
from  #cart c(nolock),CouponsMember m(nolock),Coupon p(nolock)                            
where isnull(c.couponID,0)>0                                        
and m.UID=c.couponID
and m.couponid=p.couponid                                        
group by c.couponID,p.couponvalue                                      
                                                                        
update c                                        
set CouponMoney=d.coupongoodsmoney, --参与优惠券的商品总价                                       
couponvalue=d.couponvalue,--优惠券值                                      
coupongoodsmoney=convert(float,d.couponvalue*isnull(c.pmtprice,memberprice))/d.coupongoodsmoney*c.Quantity, --商品优惠金额                                       
AvgCouponMoney=convert(float,d.couponvalue*isnull(c.pmtprice,memberprice))/d.coupongoodsmoney   --商品单价优惠金额                                      
from  #cart c(nolock),#couponDetail d(nolock)                                        
where d.couponID=c.couponID

/*=============================商品判断开始=================================*/
print('判断购物车中是否存在商品')
if not exists(select top 1 cartid from #cart)                                     
begin                                          
print('错误,购物车中不存在商品信息!')                                                
select @errorMsg='错误,购物车中不存在商品信息!'                  
,@errorFlag =1                                         
return @orderid                                          
end
/*=============================商品判断结束=================================*/


/*=============================库存控制开始=================================*/
begin tran
declare @cartnumber int,@EffectRows int 
print('商品库存控制')  
--统计商品数量                
select t.goodsid,Quantity=sum(t.Quantity)                  
into #groupcart                  
from #cart t(nolock)                             
group by t.goodsid 
                 
select @cartnumber=count(1) from #groupcart(nolock)                    
--更新商品goods表中的库存数量                  
update g set storage=g.Storage-c.quantity                  
from goods g(nolock),#groupcart c(nolock)                  
where                  
g.goodsid=c.goodsid                  
and g.Storage-c.Quantity>=0                 
                  
select @EffectRows=@@rowcount                  
                  
--有商品库存不足                  
if(@EffectRows<@cartnumber)             
begin                  
print('购物车的商品库存不足') 
select @errorflag=1, @errormsg='购物车的商品库存不足'                              
rollback 
return @orderid              
end        
/*=============================库存控制结束=================================*/                                            
--获取商品总价,总重量，总的赠送积分                                              
select                                               
@orlPdtPrice=sum(t.memberprice*t.Quantity),
@pmtPdtPrice=sum(submoney),
@pmtSubPrice=sum(LessMoney),
@couponmoney=sum(coupongoodsmoney),
@scoreSubMoney=sum(scoremoney),
@weight=sum(subweight),                                            
--@subscore=SUM(Score*t.Quantity),
@subscore=SUM(Score),
@usedscore=sum(t.usescore+t.giftscore*t.Quantity),                                              
@quantity=SUM(t.Quantity)                                              
from #cart t
--,Product p(nolock)                                               
--where p.ProductID = t.ProductID

--计算发票税金
print('计算发票税金')
select @taxPrice=@pmtPdtPrice*@taxRate	--发票税金等于商品总额乘于税率

/*=============================计算运费开始=================================*/ 
print('计算运费')
exec dbo.XpProc_CartShipPrice_Get @cartid,@payType,@subAreaID,@shippingID,@weight,@pmtPdtPrice,@memberid,@supplierid,@shipprice out

/*=============================计算运费结束=================================*/ 

--统计订单总额
print('统计订单总额')
--订单总额等于优惠后的商品总价+配送费+发票税金-优惠券抵扣金额-积分抵扣金额
select @totalPrice=@pmtPdtPrice+isnull(@shipPrice,0)+@taxPrice-isnull(@couponmoney,0)-@scoreSubMoney

print('计算可使用预付款金额')
if @useadvpay=1
begin
if @advancePayment>=@totalPrice
select @usedAdvPayment=@totalPrice,@status=2
else
select @usedAdvPayment=@advancePayment,@status=case when @advancePayment>0 then 1 else 0 end
end
else
begin
select @usedAdvPayment=0
end

print('计算还需付款金额')
select @needpaymoney=@totalPrice-@usedAdvPayment

/*========================计算货到付款手续费开始=============================*/
print('计算货到付款手续费')
if(@payType=5)--采用货到付款方式才需要计算货到付款手续费
begin
	declare @fees decimal(18,2),--手续费
	@feesType int--0为净手续费，1为总金额的百分比
	select @fees=0,@feesType=0
	select @fees=Fees,@feesType=FeesType from ShippPay where ShippAreaID=@subAreaID and ShippID=@shippingID
	if(@feesType=0)
	begin
	select @cltCharge=isnull(@fees,0)
	end
	else
	begin
	select @fees=@fees/100
	select @cltCharge=@needpaymoney*isnull(@fees,0)
	end
end
/*========================计算货到付款手续费结束=============================*/ 

print('还需付款金额需要加上货到付款手续费')
select @needpaymoney=@needpaymoney+@cltCharge

print('生成订单编号')
declare @ordercount nvarchar(10)
Select @ordercount=count(orderid)+1 from orders Where DateDiff(dd,ordertime,GetDate())=0  --当天订单总数
select @orderNo=replace(replace(convert(varchar(13),getdate(),120),'-',''),' ','')                                  
select @orderNo=replace(@orderNo,'.','')   --转为2011012316                                    
select @orderNo=right(@orderNo,8) + right('000'+ cast(@ordercount as nvarchar(10)),4) --取时间的后8位+当天订单总数(若订单总数长度超过4,只取最后的4位) 
/*=============================订单生成=================================*/
print('插入订单主体信息') 
insert into orders(
MemberID,
OrderTime,
ShipTime,
BuyerName,
BuyerPhone,
BuyerMobile,
BuyerEmail,
BuyerAddress,
BuyerPostalcode,
ReceiverName,
ReceiverPhone,
ReceiverMobile,
ReceiverEmail,
ReceiverAddress,
ReceiverPostalcode,
Remark,
TotalPrice,
NeedPayMoney,
LessMoney,
ProductPrice,
CustomItemPrice,
Discount,
ShipPrice,
AdvancePayment,
PaymentType,
ShippingType,
Score,
Weight,
Quantity,
NeedInvoice,
TaxPrice,
CltCharge,
PayType,
Status,
ManageHistory,
LastModify,
OrderNo,
Code,
IsAgentF,
IsAgentFContent,
IsShippingFree,
Type,
Favourable,
ZtdNo,
IsToErp,
OrderType,
IsToMessage,
AddMethod,
AddressID,
UsedScore,
ScoreAmount,
CouponValue,
SupplierID
) 
values
(
@memberID,
@ordertime,
@shippingTime,
'',
'',
'',
'',
'',
'',
@rName,
@rPhone,
@rMobile,
@rEmail,
@rAddress,
@rPostalcode,
@remark,
@totalPrice,--订单总额
@needpaymoney,--还需支付金额
@pmtSubPrice,--订单优惠金额
@pmtPdtPrice,--商品总额
0,--配件价格
100,
@shipPrice,
@usedAdvPayment,
0,--以前是paymentID,现在不用存支付方式ID,只需要存payType
@shippingID,
@subscore,
@weight,
@quantity,
@needInvoice,
@taxPrice,
@cltCharge,
@payType,
@status,
'',--订单管理日志
0,--最后更新时间
@orderNo,--订单编号
@code,
@isAgentF,
@agentFContent,
@isShippingFree,
@orderType,
@favourable,
@ztdNo,
0,
0,
0,
1,
@addressID,
@usedScore,
@scoreSubMoney,
@couponmoney,
@supplierid
)   
select @orderID=@@Identity                                        
/*=============================订单生成结束=================================*/
/*===========================订单明细生成开始===============================*/
print('插入订单明细')                                            
insert into OrderProduct                                               
(
OrderID,OrderNo,ProductID,Quantity,CostPrice,MemberPrice,--1                                              
UnitPrice,SubPrice,LessMoney,Remark,IsDiscount, --2                                             
ProductName,ProductNo,ThumbnailImg,CategoryID, --3                                             
BrandID,GoodsID,UsedScore,Ptype,StowageID, --4
IsOfferInvoice,                                          
RuleID,--规则ID                                          
RuleName,--规则名称                                          
PmtID,--促销ID                                          
PmtName,--促销活动名称                                         
CouponsMemberID,
CouponValue,
CouponGoodsMoney,
AvgCouponMoney,--优惠券信息 
IsNeedStowage,--是否需要库存  
SupplierID,--商家ID  
Stockout,--未发货数量
MemberID,--会员ID
OrderTime,--购买时间 
Score,--赠送积分  
PackingList --包装清单     
) 
select 
@OrderID,@OrderNo,p.ProductID,sc.Quantity,p.CostPrice,g.MemberPrice,--1                                            
isnull(sc.pmtprice,sc.memberprice) pmtprice,isnull(sc.submoney,0) Submoney,isnull(sc.LessMoney,0) LessMoney,sc.remark,sc.IsDiscount,--2                
p.ProductName,g.goodsno,p.ThumbnailImg,p.CategoryID,--3                                              
p.BrandID,g.GoodsID,0,sc.ptype,0 StowageID,--4                                    
p.IsOfferInvoice,
sc.ruleid ,--规则ID                                          
sc.RuleName ,--规则名称                                          
sc.pmtid  ,--促销ID                                          
sc.PmtName ,--促销活动名称                                                                       
sc.CouponID,
sc.couponvalue,
sc.coupongoodsmoney,
sc.AvgCouponMoney,--优惠券信息
sc.isNeedStowage,--是否需要库存
sc.supplierid,
sc.quantity,
@memberid as memberid,
@ordertime as ordertime, 
sc.score,
p.packinglist                                                                                  
from Product as p(nolock),#cart as sc(nolock),Goods as g(nolock)                                               
where                              
p.ProductID = sc.ProductID                                                 
AND sc.GoodsID = g.GoodsID                                               
and g.ProductID = p.ProductID                                               
--AND sc.CartID = @cartID  
order by sc.sort
/*===========================订单明细生成结束===============================*/

/*=========================更改秒杀记录开始==============================*/ 
update memberbookseckill set orderid=@orderid,orderno=@orderno,ordertime=@ordertime,status=1 where uid=@cartid
/*=========================更改秒杀记录结束==============================*/ 

/*=========================记录发票信息开始==============================*/                          
print('记录发票信息')
if @needInvoice=1
begin
exec XpProc_OrderInvoice_Insert @orderid,@invoiceType,@invoiceHead,@isDetails,@invoiceContent,@memberid
end
/*=========================记录发票信息结束==============================*/

/*=========================下订单预赠送积分开始==============================*/                          
print('预送积分暂时不做')
/*=========================下订单预赠送积分结束==============================*/                                          
                          
/*=========================使用及赠送优惠券开始==============================*/
print('更新优惠券信息')                                                                              
--使用优惠券,需要更新优惠券信息                                        
select distinct p.orderid,p.CouponsMemberID                                        
into #newordercoupon                                        
from orderproduct p(nolock)                                        
where p.orderid=@orderid                                        
--更新优惠券的使用情况                                        
update m                                        
set Status=case when m.ispublic=1 then 1 else 0 end,UsedTimes=UsedTimes+1,IsUsed=case when m.ispublic=1 then 0 else 1 end,UsedTime=getdate(),UseUserID=@memberid,m.OrderID=n.OrderID,m.orderno=@orderNo                                      
from                                         
CouponsMember m(nolock),#newordercoupon n(nolock)                                        
where n.CouponsMemberID=m.UID                                        
--添加使用优惠券记录                                        
insert into CouponsUsedItems(OrderID,OrderNo,CouponID,CouponName,CouponCode,UseUserID,SupplierID)              
select n.OrderID,@orderno,m.UID,c.CouponName,m.CouponCode,@memberid,@supplierid                                        
from #newordercoupon n(nolock),Coupon c(nolock),CouponsMember m(nolock)
where n.CouponsMemberID=m.UID
and m.CouponID = c.CouponID

--记录待赠送的优惠券
select p.*
into #c
from
(
--订单满额返券
select c.couponid,c.number,c.number as subnumber,r.ruleid,r.rulename,null as productid,null as goodsid
from pmtrule r(nolock),pmtcoupons c(nolock)
where r.basictype='orders' and r.subtype='coupon' and minvalue<@pmtpdtprice and getdate() between BeginTime and EndTime and r.ruleid=c.ruleid and r.supplierid=@supplierid
union
--单品返券
select c.couponid,c.number,c.number*t.quantity as subnumber,r.ruleid,r.rulename,g.productid,g.goodsid
from #cart t,pmtrule r(nolock),pmtgoods g(nolock),pmtcoupons c(nolock)
where t.productid=g.productid and g.ruleid=r.ruleid and r.basictype='goods' and r.subtype='coupon' and getdate() between BeginTime and EndTime and c.ruleid=r.ruleid and r.supplierid=@supplierid
) as p

insert into ordercoupon(memberid,membername,cartid,orderid,orderno,couponid,couponname,couponvalue,suittype,suitvalue,
MinMoney,begintime,endtime,number,subnumber,productid,goodsid,ruleid,rulename,supplierid,sendreason,ip,status)
select @memberid,@membername,@cartid,@orderid,@orderno,c.couponid,c.couponname,c.couponvalue,c.suittype,c.suitvalue,
c.minmoney,c.begintime,c.endtime,t.number,t.subnumber,t.productid,t.goodsid,t.ruleid,t.rulename,@supplierid,t.rulename,@addIP,0 as status
from #c t,coupon c(nolock)
where t.couponid=c.couponid
/*=========================使用及赠送优惠券结束==============================*/ 

/*========================扣减预付款开始==============================*/
declare @usedremark varchar(100)
select @usedremark = '预付款支付订单:'+@orderno
select  @usedAdvPayment=-@usedAdvPayment   
exec XpProc_AdvancePayment_Add @memberid,@membername,@usedAdvPayment,-1,'system',@usedremark,@errorflag out,@errormsg out
/*========================扣减预付款开始==============================*/     

/*========================更新地址簿开始==============================*/
if @shipAddressID>0
begin
exec XpProc_ReceiverAddress_Update @shipAddressID,@rName,@rAddress,@rPostalcode,@rPhone,@rMobile,@MemberID,@AddressID,@rEmail                              
end
else
begin
if @isSaveAddress=1
exec XpProc_ReceiverAddress_Insert @rName,@rAddress,@rPostalcode,@rPhone,@rMobile,@MemberID,@AddressID,@rEmail
end
/*========================更新地址簿结束==============================*/ 
                                       
 --删除购物车内容                                       
delete from CouponCart where CartID=@cartID and supplierid=@supplierid

/*=========================记录订单生成日志开始==============================*/ 
exec XpProc_OrderOpLog_Add @orderid,@orderno,@membername,@memberid,'顾客','顾客下单','顾客下单',0,1
--如果使用了预付款要插入订单支付日志
if(@usedAdvPayment<>0)
exec XpProc_OrderOpLog_Add @orderid,@orderno,@membername,@memberid,'顾客','顾客预付款支付订单','顾客预付款支付订单',@status,1
/*=========================记录订单生成日志结束==============================*/  
select @errorflag=0,@errormsg=''
commit  
End Try

Begin Catch
--回滚事务
rollback
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1,@orderid=-1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch                                      
end





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderStatistics]    脚本日期: 04/09/2012 18:27:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_OrderStatistics]
@sid int, --要统计的商家的ID
@Flag bit --标记是按月还是按日来统计订单,
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	declare @StartTime smalldatetime
	declare @EndTime smalldatetime
	declare @TempTime smalldatetime
	declare @Table table(Mday smalldatetime primary key)
	--@Flag=0说明是按日来查看近三十天的记录，否则是按月来查看近十二个月的记录
if(@Flag=0)
	begin
		--根据当前的时间，生成一个包含一个月的日期的日期表
		set @StartTime=getDate()
		set @EndTime =dateadd(mm,-1,getDate())
		set @TempTime=@StartTime
		while(@TempTime>@EndTime)
		begin
		insert @Table values(@TempTime)
		set @TempTime=dateadd(dd,-1,@TempTime)
		end
		--Orders表中的OrderTime,SendTime,ReciveTime ,CancelTime分别为下单，发货，收货，取消时间

		--通过连接@Table,找出一个月内的已发货的订单
		select Convert(varChar(10),t.mday ,112) as SendTime ,
		count(SendTime) as SendNum, 
		isnull(sum( TotalPrice),0) as SendAmount,
		case when count(SendTime)<>0 then isnull(sum( TotalPrice),0)/count(SendTime) else 0 end as SendAvg 
		into #Send1
		from  @Table t left join  Orders o(nolock)
		on convert(varchar(10),o.Sendtime,112)=convert(varchar(10),t.mday,112) and o.supplierid=@sid
		group by Convert(varChar(10),t.mday ,112) 
		--	order by Convert(varChar(10),t.mday ,112) desc
		
		--通过连接@Table,找出一个月内的已下的订单
		select Convert(VarChar(10),t.mday ,112) as OrderTime ,
		count(Ordertime) as OrderNum, 
		isnull(sum( TotalPrice),0) as OrderAmount,
		case when count(Ordertime)<>0 then isnull(sum( TotalPrice),0)/count(Ordertime) else 0 end as OrderAvg 
		into #Add1
		from  @Table t left join  Orders o (nolock)
		on convert(varchar(10),o.OrderTime,112)=convert(varchar(10),t.mday,112) and o.supplierid=@sid
		group by Convert(varChar(10),t.mday ,112) 
		--	order by Convert(varChar(10),t.mday ,112) desc
	
		--通过连接@Table,找出一个月内的已取消的订单
		select Convert(varChar(10),t.mday ,112) as CancelTime ,
		count(CancelTime) as CancelNum, 
		isnull(sum( TotalPrice),0) as CancelAmount,
		case when count(CancelTime)<>0 then isnull(sum( TotalPrice),0)/count(CancelTime) else 0 end as CancelAvg 
		into #Cancel1
		from  @Table t left join  Orders o(nolock)
		on convert(varchar(10),o.CancelTime,112)=convert(varchar(10),t.mday,112) and o.supplierid=@sid
		group by Convert(varChar(10),t.mday ,112)
		--	order by Convert(varChar(10),t.mday ,112) desc

		--连接三张临时表，得到一个月内的下订单，发货及取消订单记录
		select a.OrderTime,a.OrderNum,a.OrderAmount,a.OrderAvg,s.SendNum,s.SendAmount,s.SendAvg,c.CancelNum,c.CancelAmount,c.CancelAvg 
		from #Add1 a join #Send1 s join #Cancel1 c on s.SendTime=c.CancelTime on s.SendTime=a.OrderTime order by a.OrderTime desc
		
		--得到一个月内下订单，发货及取消订单的总数
		select sum(a.OrderNum)as OrderNums,sum(a.OrderAmount)as OrderAmounts,
		case when sum(a.OrderNum)<>0 then (cast(sum(a.OrderAmount)/sum(a.OrderNum) as decimal(18,2)))else 0 end as OrderAvgs,
		sum(s.SendNum)as SendNums,sum(s.SendAmount)as SendAmounts,
		case when sum(s.SendNum)<>0 then (cast(sum(s.SendAmount)/sum(s.SendNum) as decimal(18,2)))else 0 end as SendAvgs,
		sum(c.CancelNum)as CancelNums,sum(c.CancelAmount)as CancelAmounts,	
		case when sum(c.CancelNum)<>0 then (cast(sum(c.CancelAmount)/sum(c.CancelNum) as decimal(18,2)))else 0 end as CancelAvgs
		from #Add1 a join #Send1 s join #Cancel1 c on s.SendTime=c.CancelTime on s.SendTime=a.OrderTime
	end
	else
	begin
		--根据当前的时间，生成一个日期表
		set @StartTime=getDate()
		set @EndTime =dateadd(mm,-12,getDate())
		set @TempTime=@StartTime
		while(@TempTime>@EndTime)
		begin
		insert @Table values(@TempTime)
		set @TempTime=dateadd(mm,-1,@TempTime)
		end

		select Convert(varChar(6),t.mday ,112) as SendTime ,
		count(SendTime) as SendNum, 
		isnull(sum( TotalPrice),0) as SendAmount,
		case when count(SendTime)<>0 then isnull(sum( TotalPrice),0)/count(SendTime) else 0 end as SendAvg 
		into #Send2
		from  @Table t left join  Orders o(nolock)
		on convert(varchar(6),o.Sendtime,112)=convert(varchar(6),t.mday,112) and o.supplierid=@sid
		group by Convert(varChar(6),t.mday ,112) 

		select Convert(varchar(6),t.mday ,112) as OrderTime ,
		count(Ordertime) as OrderNum, 
		isnull(sum( TotalPrice),0) as OrderAmount,
		case when count(OrderTime)<>0 then sum( TotalPrice)/count(OrderTime) else 0 end as OrderAvg 
		into #Add2
		from  @Table t left join  Orders o (nolock)
		on convert(varchar(6),o.OrderTime,112)=convert(varchar(6),t.mday,112) and o.supplierid=@sid
		group by Convert(varChar(6),t.mday ,112) 

		select Convert(varChar(6),t.mday ,112) as CancelTime ,
		count(CancelTime) as CancelNum, 
		isnull(sum( TotalPrice),0) as CancelAmount,
		case when count(CancelTime)<>0 then isnull(sum( TotalPrice),0)/count(CancelTime) else 0 end as CancelAvg
		into #Cancel2
		from @Table t left join  Orders o(nolock)
		on convert(varchar(6),o.CancelTime,112)=convert(varchar(6),t.mday,112) and o.supplierid=@sid
		group by Convert(varChar(6),t.mday ,112)

		--连接三张临时表，得到十二个月内的下订单，发货及取消订单记录
		select a.OrderTime,a.OrderNum,a.OrderAmount,a.OrderAvg,s.SendNum,s.SendAmount,s.SendAvg,c.CancelNum,c.CancelAmount,c.CancelAvg 
		from #Add2 a join #Send2 s join #Cancel2 c on s.SendTime=c.CancelTime on s.SendTime=a.OrderTime order by a.OrderTime desc

		--得到十二个月内下订单，发货及取消订单的总数
		select sum(a.OrderNum)as OrderNums,sum(a.OrderAmount)as OrderAmounts,
		case when sum(a.OrderNum)<>0 then (cast(sum(a.OrderAmount)/sum(a.OrderNum) as decimal(18,2)))else 0 end as OrderAvgs,
		sum(s.SendNum)as SendNums,sum(s.SendAmount)as SendAmounts,
		case when sum(s.SendNum)<>0 then (cast(sum(s.SendAmount)/sum(s.SendNum) as decimal(18,2)))else 0 end as SendAvgs,
		sum(c.CancelNum)as CancelNums,sum(c.CancelAmount)as CancelAmounts,	
		case when sum(c.CancelNum)<>0 then (cast(sum(c.CancelAmount)/sum(c.CancelNum) as decimal(18,2)))else 0 end as CancelAvgs
		from #Add2 a join #Send2 s join #Cancel2 c on s.SendTime=c.CancelTime on s.SendTime=a.OrderTime
	end
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderStatus_BatchUpdate]    脚本日期: 04/09/2012 18:27:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-06-29>
-- Description:	<作业，用于根据时间批量更改订单的状态>
-- =============================================
CREATE PROC [dbo].[XpProc_OrderStatus_BatchUpdate]
@CancelCount varchar(100) output,
@FinishCount varchar(100) output,
@SignCount varchar(100) output
AS
begin
	--以下三个参数用于保存订单里的商品ID，货品ID跟购买数量，传给XpProc_ProductStorage_Update以更新商品的数量及skumap
	declare @productids varchar(8000),@goodsids varchar(8000),@quantitys varchar(8000)
	select @productids='',@goodsids='',@quantitys=''

	--规定时间内（3天）未付款的订单，并标识为交易取消
	declare @count int
	begin try
		begin tran
			select orderid into #temp1 from orders(nolock) where status=0 and  datediff(day,ordertime,getDate())>3
			declare @cancel_orderid int 
			declare cancel_orderid cursor for
			select orderid from #temp1 order by orderid 
			open cancel_orderid
			fetch next from cancel_orderid into @cancel_orderid
			while @@fetch_status=0
			begin
			--更新商品的库存量
--			exec XpProc_ProductStorage_Update @cancel_orderid,1
--			更新商品的库存量,跟盘点库存共用一个存储过程
			select @productids=@productids+','+cast(productid as varchar),
			@goodsids=@goodsids+','+cast(goodsid as varchar),@quantitys=@quantitys+','+cast(quantity as varchar)
			from orderproduct (nolock) where orderid=@cancel_orderid
			select @productids=stuff(@productids,1,1,''), @goodsids=stuff(@goodsids,1,1,''), @quantitys=stuff(@quantitys,1,1,'')
			exec XpProc_ProductStorage_Update @productids,@goodsids,@quantitys,1
			--更改待返券的状态为已取消
			update ordercoupon set status=-1 where orderid=@cancel_orderid
			--写日志操作
			exec XpProc_OrderOpLog_Add @cancel_orderid,null,'系统',null,'系统','取消：超时取消单','取消：超时取消',10,1
			fetch next from cancel_orderid into @cancel_orderid
			end
			close cancel_orderid
			deallocate cancel_orderid
			update orders set status=10,canceltype=case when paytype<5 then '超时未支付,系统自动取消订单' else '超时未确认,系统自动取消订单' end,canceltime=getdate() from #temp1 where orders.orderid=#temp1.orderid
			select @count=count(orderid)from #temp1
			select @CancelCount='这次作业共取消'+cast(@count as varchar(10))+'个超时订单'
		commit tran
	end try
	begin catch
		rollback tran
	end catch

	--签收后过了一定时间（3天）的订单，并标识为交易完成
	begin try
		begin tran
			declare @errorflag int,@errormsg varchar(200)
			select orderid into #temp2 from orders(nolock)where status=7 and  datediff(day,receivetime,getDate())>3
			declare @finish_orderid int 
			declare finish_orderid cursor for
			select orderid from #temp2 order by orderid 
			open finish_orderid
			fetch next from finish_orderid into @finish_orderid
			while @@fetch_status=0
			begin
			exec XpProc_Order_Complete @finish_orderid,null,'系统','系统','系统默认订单交易完成',@errorflag out,@errormsg out
			fetch next from finish_orderid into @finish_orderid
			end
			close finish_orderid
			deallocate finish_orderid
			--update orders set status=12,FinishTime=getdate() from #temp2 where orders.orderid=#temp2.orderid
			select @count=count(orderid)from #temp2
			select @finishcount='这次作业共更新了'+cast(@count as varchar(10))+'个订单为交易成功'
		commit tran
	end try
	begin catch
		rollback tran
	end catch
	--select receivetime,datediff(day,receivetime,getDate()) from orders where status=7 and  datediff(day,receivetime,getDate())>15
	--update orders set status=12 where status=7 and  receiveTime<convert(varchar(10),dateadd(day,-15,getDate()),120)

	--发货10天后的商品，如果还没有签收，系统自动置为已签收
	begin try
		begin tran
			select orderid into #temp3 from orders(nolock) where status=6 and  datediff(day,sendtime,getDate())>10
			declare @sign_orderid int 
			declare sign_orderid cursor for
			select orderid from #temp3 order by orderid 
			open sign_orderid
			fetch next from sign_orderid into @sign_orderid
			while @@fetch_status=0
			begin
			--更新OrderProduct表中的COMMENTSTATUS为可评价
			update orderProduct set commentstatus=1 where orderid=@sign_orderid
			--写日志操作
			exec XpProc_OrderOpLog_Add @sign_orderid,null,'系统',null,'系统','签收：超时系统默认顾客已签收','签收：超时系统默认顾客已签收',7,1
			fetch next from sign_orderid into @sign_orderid
			end
			close sign_orderid
			deallocate sign_orderid
--			update orders set status=7 where orderid in(select orderid from #temp3)
			update orders set status=7,receivetime=getdate() from #temp3 where orders.orderid=#temp3.orderid
			select @count=count(orderid)from #temp3
			select @SignCount='这次作业共签收'+cast(@count as varchar(10))+'个订单'
		commit tran
	end try
	begin catch
		rollback tran
	end catch
end

--declare @cancelcount varchar(100)
--declare @finishcount varchar(100)
--declare @signcount varchar(100)
--exec XpProc_OrderStatus_BatchUpdate @cancelcount output,@finishcount output,@signcount output
--select @cancelcount,@finishcount,@signcount

--测试取消订单
--1、商品的库存
--2、订单的日志
--测试订单交易完成
--1、商品的销量
--2、会员的积分及消费金额、会员组，积分日志
--3、日志
--   以下没有实现
--4、处理优惠券的
--5、处理礼品的
--6、处理代销
--7、购买记录






















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderTG_BatchMake]    脚本日期: 04/09/2012 18:27:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-05-20>
-- Description:	<添加团购订单>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_OrderTG_BatchMake]                 
@uids varchar(8000),
@memberid int ,--操作员ID
@errorMsg varchar(200)='' out,--错误信息提示        
@errorFlag int =0 out--是否错误标识，<>0时，显示错误信息，并返回购物车界面 
AS                                           
begin
insert log(content)values(@uids)
declare @uid varchar(36)
select * into #t from SplitToTable_Func(@uids,',')
declare memberbooktg_cursor cursor for select value from #t
open memberbooktg_cursor                                              
fetch next from memberbooktg_cursor into @uid
while @@fetch_status = 0
begin 
exec XpProc_OrderTG_Make @uid
fetch next from memberbooktg_cursor into @uid
end
close memberbooktg_cursor                                              
deallocate memberbooktg_cursor	
end












GO
/****** 对象:  StoredProcedure [dbo].[XpProc_OrderTG_Make]    脚本日期: 04/09/2012 18:27:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-05-20>
-- Description:	<添加团购订单>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_OrderTG_Make]                 
@uid varchar(max),
@errorMsg varchar(200)='' out,--错误信息提示        
@errorFlag int =0 out,--是否错误标识，<>0时，显示错误信息，并返回购物车界面 
@orderID int=null out, --订单ID
@orderNo nvarchar(30)=null out,--订单编号
@usedScore int=null out,--使用的总积分
@scoreSubMoney decimal(18,2)=null out,--积分抵扣的总金额
@usedAdvPayment decimal(18,2)=null out,--使用的预付款金额
@pmtPdtPrice decimal(18,2)=null out,--优惠后商品总价
@totalPrice decimal(18,2)=null out--订单总价
AS                                           
begin
--设置订单的默认信息 
select @errorMsg='',@errorFlag =1,@orderid=-1,@orderNo='',@usedScore=0,@scoreSubMoney=0,@usedAdvPayment=0,@pmtPdtPrice=0,@totalPrice=0
print('新订单的生成..')                               
declare @orlPdtPrice decimal(18,2),--优惠前商品总价
@pmtSubPrice decimal(18,2),--享受的优惠总额
@subscore int,--获得的总积分
@shipPrice decimal(18,2),--配送价格
@taxPrice decimal(18,2),--税率
@weight decimal(18,2),--重量
@cltCharge decimal(18,2),--货到付款手续费
@quantity int,--商品数量
@isAgentF int,
@isShippingFree int,--是否免运费                                   
@sql nvarchar(1000),
@favourable nvarchar(500),--优惠信息
@couponmoney money,--优惠券优惠金额
@membermobile varchar(50),--会员手机号
@memberscore int,--会员当前可使用积分
@groupname nvarchar(20),--会员组名称
@discount nvarchar(20),--会员组折扣
@agentFContent nvarchar(100),
@status int,--订单状态
@ordertime datetime, --下订时间
@advancePayment decimal(18,2), --会员的电子账户余额
@needpaymoney decimal(18,2),--还需支付金额
@memberid int,
@membername nvarchar(100),--会员账号
@rName nvarchar(20),--收货人姓名
@rEmail nvarchar(20),--收货人EMAIL
@rMobile nvarchar(20),--收货人联系手机
@rPhone nvarchar(20),--收货人联系电话
@rPostalcode nvarchar(20),--收货人邮编
@rAddress  nvarchar(100),--收货人详细地址
@topAreaID int,--省级ID
@subAreaID int,--市级ID
@thirdAreaID int,--县区级ID
@isSaveAddress int,--是否保存收货人地址到地址簿    
@shipAddressID int,--地址簿ID,
@payType int,--支付类型
@shippingID int,--配送方式
@shippingTime nvarchar(50), --送货时间
@code nvarchar(20),--代销人的代销号
@useadvpay tinyint,--是否使用预付款
@needInvoice tinyint,  --是否需要发票    
@invoiceType int,--发票类型
@invoiceHead nvarchar(50),--发票抬头
@isDetails tinyint,--发票内容是否为订单明细
@invoiceContent nvarchar(300),--发票内容
@taxRate decimal(18,2),--税金比例
@remark nvarchar(300),  --Remark 备注                                    
@orderType int,--订单类型:1为正常下订流程的订单,2为团购,3拍卖的订单,4为合并的订单                                                               
@addMethod int,   --AddMethod 下订方式,1是会员在线下的订单,2是管理员代订                                    
@ztdID int,   --取货门店ID   
@ztdNo varchar(20),   --取货门店编号 
@ztdAdminName varchar(100),--代下订单管理员账号                              
@ztdAdminID int, --代订管理员ID
@addIP varchar(50), --下订单人的IP地址
@supplierid int,--商家ID
@AddressID nvarchar(50)
--初始化变量值
select @isShippingFree=0,@shipPrice=20,@taxPrice=0,@cltCharge=0,@isAgentF=0,@agentFContent='',@favourable='',@status=0,@ordertime=getdate(),@advancePayment=0          
,@memberid =null,
@topAreaID =null,
@subAreaID =null,--市级ID
@thirdAreaID =null,--县区级ID
@isSaveAddress=0,--是否保存收货人地址到地址簿    
@shipAddressID =null,--地址簿ID,
@payType =1,--支付类型
@shippingID =1,--配送方式
@shippingTime ='任意日期　任意时间段', --送货时间
@code ='admin',--代销人的代销号
@useadvpay =0,--是否使用预付款
@needInvoice =0,  --是否需要发票    
@invoiceType =null,--发票类型
@invoiceHead =null,--发票抬头
@isDetails =null,--发票内容是否为订单明细
@invoiceContent =null,--发票内容
@taxRate =null,--税金比例
@remark ='团购订单',  --Remark 备注                                    
@orderType =2,--订单类型:1为正常下订流程的订单,2为团购,3拍卖的订单,4为合并的订单                                                               
@addMethod =1,   --AddMethod 下订方式,1是会员在线下的订单,2是管理员代订                                    
@ztdID =null,   --取货门店ID   
@ztdNo ='',   --取货门店编号 
@ztdAdminName =null,--代下订单管理员账号                              
@ztdAdminID =null, --代订管理员ID
@addIP ='', --下订单人的IP地址
@supplierid =null,--商家ID    
@AddressID=''
select @supplierid=supplierid, @memberid=memberid,@rName=receivername,@rPhone=receiverphone,@rMobile=receivermobile,@rEmail='',@rAddress=receiveraddress,@rPostalcode=receiverpostalcode
from memberbooktg(nolock)where uid=@uid

Begin Try
begin tran                           
print('商品信息')

select * into #cart 
from (select cartid=@uid,mb.goodsid,mb.productid,g.goodsno,pm.marketprice,pm.memberprice,g.weight,mb.RuleName,                                        
pm.pmtprice,mb.quantity,
subweight=0,submoney=mb.quantity*mb.pmtprice,lessmoney=0,                                          
pmtname,mb.ruleid,basictype,subtype,remark='团购商品',1 ptype,0 giftscore,convert(nvarchar(20),'goods') PmtType                                         
,pmtid ,0 couponID,couponvalue=convert(money,0),coupongoodsmoney=convert(money,0),                                        
CouponMoney=convert(float,0),AvgCouponMoney=convert(float,0),
ProductSpecs='',isneedstowage=0,
0 isdiscount,
 0 score, 0 usescore,
 0 ScoreMoney,pm.supplierid,0 suit , 0 sort
from  memberbooktg mb(nolock),pmtgoods pm(nolock),goods g(nolock)
where mb.uid=@uid and mb.status=0 and mb.goodsid=pm.goodsid and mb.goodsid=g.goodsid)as temp

/*=============================商品判断开始=================================*/
print('判断购物车中是否存在商品')
if not exists(select top 1 cartid from #cart)                                     
begin                                          
print('错误,购物车中不存在商品信息!')                                                
select @errorMsg='错误,购物车中不存在商品信息!'                  
,@errorFlag =1                                         
return @orderid                                          
end
/*=============================商品判断结束=================================*/

/*=============================库存控制开始=================================*/
declare @cartnumber int,@EffectRows int 
print('商品库存控制')  
--统计商品数量                
select mb.goodsid,Quantity=(mb.Quantity)                  
into #groupcart                  
from  memberbooktg(nolock) mb where mb.uid=@uid and mb.status=0    
--group by mb.goodsid 
                 
select @cartnumber=count(1) from #groupcart(nolock)                    
--更新商品goods表中的库存数量                  
update g set storage=g.Storage-c.quantity                  
from goods g(nolock),#groupcart c(nolock)                  
where                  
g.goodsid=c.goodsid                  
and g.Storage-c.Quantity>=0                 
                  
select @EffectRows=@@rowcount                  
                  
--有商品库存不足                  
if(@EffectRows<@cartnumber)             
begin                  
print('购物车的商品库存不足') 
select @errorflag=1, @errormsg='购物车的商品库存不足'                              
rollback 
return @orderid              
end        
/*=============================库存控制结束=================================*/                                            
--获取商品总价,总重量，总的赠送积分                                              
select                                               
@orlPdtPrice=sum(t.memberprice*t.Quantity),
@pmtPdtPrice=sum(submoney),
@pmtSubPrice=sum(LessMoney),
@couponmoney=sum(coupongoodsmoney),
@scoreSubMoney=sum(scoremoney),
@weight=sum(subweight),                                            
@subscore=SUM(Score*t.Quantity),
@subscore=SUM(Score),
@usedscore=sum(t.usescore+t.giftscore*t.Quantity),                                              
@quantity=SUM(t.Quantity)                                          
from #cart t
--,Product p(nolock)                                               
--where p.ProductID = t.ProductID

/*=============================计算运费开始=================================*/ 
print('计算运费')
select @shipPrice=0
/*=============================计算运费结束=================================*/ 

--统计订单总额
print('统计订单总额')
--订单总额等于优惠后的商品总价+配送费+发票税金-优惠券抵扣金额-积分抵扣金额
--select @totalPrice=isnull(@pmtPdtPrice,0)+isnull(@shipPrice,0)+isnull(@taxPrice,0)+isnull(@cltCharge,0)-isnull(@scoreSubMoney,0)-isnull(@advancePayment,0)
select @totalPrice=@pmtPdtPrice+isnull(@shipPrice,0)+@taxPrice-isnull(@couponmoney,0)-@scoreSubMoney
print('生成订单编号')
declare @ordercount nvarchar(10)
Select @ordercount=count(orderid)+1 from orders Where DateDiff(dd,ordertime,GetDate())=0  --当天订单总数
select @orderNo=replace(replace(convert(varchar(13),getdate(),120),'-',''),' ','')                                  
select @orderNo=replace(@orderNo,'.','')   --转为2011012316                                    
select @orderNo=right(@orderNo,8) + right('000'+ cast(@ordercount as nvarchar(10)),4) --取时间的后8位+当天订单总数(若订单总数长度超过4,只取最后的4位) 
/*=============================订单生成=================================*/
print('插入订单主体信息') 
insert into orders(
MemberID,
OrderTime,
ShipTime,
BuyerName,
BuyerPhone,
BuyerMobile,
BuyerEmail,
BuyerAddress,
BuyerPostalcode,
ReceiverName,
ReceiverPhone,
ReceiverMobile,
ReceiverEmail,
ReceiverAddress,
ReceiverPostalcode,
Remark,
TotalPrice,
NeedPayMoney,
LessMoney,
ProductPrice,
CustomItemPrice,
Discount,
ShipPrice,
AdvancePayment,
PaymentType,
ShippingType,
Score,
Weight,
Quantity,
NeedInvoice,
TaxPrice,
CltCharge,
PayType,
Status,
ManageHistory,
LastModify,
OrderNo,
Code,
IsAgentF,
IsAgentFContent,
IsShippingFree,
Type,
Favourable,
ZtdNo,
IsToErp,
OrderType,
IsToMessage,
AddMethod,
AddressID,
UsedScore,
ScoreAmount,
CouponValue,
SupplierID
) 
values
(
@memberID,
@ordertime,
@shippingTime,
'',
'',
'',
'',
'',
'',
@rName,
@rPhone,
@rMobile,
@rEmail,
@rAddress,
@rPostalcode,
@remark,
@totalPrice,--订单总额
@needpaymoney,--还需支付金额
@pmtSubPrice,--订单优惠金额
@pmtPdtPrice,--商品总额
0,--配件价格
100,
@shipPrice,
@usedAdvPayment,
0,--以前是paymentID,现在不用存支付方式ID,只需要存payType
@shippingID,
@subscore,
@weight,
@quantity,
@needInvoice,
@taxPrice,
@cltCharge,
@payType,
@status,
'',--订单管理日志
0,--最后更新时间
@orderNo,--订单编号
@code,
@isAgentF,
@agentFContent,
@isShippingFree,
@orderType,
@favourable,
@ztdNo,
0,
0,
0,
1,
@addressID,
@usedScore,
@scoreSubMoney,
@couponmoney,
@supplierid
)   
select @orderID=@@Identity                                        
/*=============================订单生成结束=================================*/
/*===========================订单明细生成开始===============================*/
print('插入订单明细')                                            
insert into OrderProduct                                               
(
OrderID,OrderNo,ProductID,Quantity,CostPrice,MemberPrice,--1                                              
UnitPrice,SubPrice,LessMoney,Remark,IsDiscount, --2                                             
ProductName,ProductNo,ThumbnailImg,CategoryID, --3                                             
BrandID,GoodsID,UsedScore,Ptype,StowageID, --4
IsOfferInvoice,                                          
RuleID,--规则ID                                          
RuleName,--规则名称                                          
PmtID,--促销ID                                          
PmtName,--促销活动名称                                         
CouponsMemberID,
CouponValue,
CouponGoodsMoney,
AvgCouponMoney,--优惠券信息 
IsNeedStowage,--是否需要库存  
SupplierID,--商家ID  
Stockout,--未发货数量
MemberID,--会员ID
OrderTime,--购买时间 
Score,--赠送积分  
PackingList --包装清单     
) 
select 
@OrderID,@OrderNo,p.ProductID,sc.Quantity,p.CostPrice,g.MemberPrice,--1                                            
isnull(sc.pmtprice,sc.memberprice) pmtprice,isnull(sc.submoney,0) Submoney,isnull(sc.LessMoney,0) LessMoney,sc.remark,sc.IsDiscount,--2                
p.ProductName,g.goodsno,p.ThumbnailImg,p.CategoryID,--3                                              
p.BrandID,g.GoodsID,0,sc.ptype,0 StowageID,--4                                    
p.IsOfferInvoice,
sc.ruleid ,--规则ID                                          
sc.RuleName ,--规则名称                                          
sc.pmtid  ,--促销ID                                          
sc.PmtName ,--促销活动名称                                                                       
sc.CouponID,
sc.couponvalue,
sc.coupongoodsmoney,
sc.AvgCouponMoney,--优惠券信息
sc.isNeedStowage,--是否需要库存
sc.supplierid,
sc.quantity,
@memberid as memberid,
@ordertime as ordertime, 
sc.score,
p.packinglist                                                                                  
from Product as p(nolock),#cart as sc(nolock),Goods as g(nolock)                                               
where                              
p.ProductID = sc.ProductID                                                 
AND sc.GoodsID = g.GoodsID                                               
and g.ProductID = p.ProductID                                               
--AND sc.CartID = @cartID  
order by sc.sort
/*===========================订单明细生成结束===============================*/

/*=========================更改团购物记录的状态开始==============================*/ 
update memberbooktg set orderid=@orderid,orderno=@orderno,ordertime=@ordertime,status=1 where uid=@uid
/*=========================更改团购物记录的状态结束==============================*/ 

--
--/*========================更新地址簿开始==============================*/
--if @shipAddressID>0
--begin
--exec XpProc_ReceiverAddress_Update @shipAddressID,@rName,@rAddress,@rPostalcode,@rPhone,@rMobile,@MemberID,@AddressID,@rEmail                              
--end
--else
--begin
--if @isSaveAddress=1
--exec XpProc_ReceiverAddress_Insert @rName,@rAddress,@rPostalcode,@rPhone,@rMobile,@MemberID,@AddressID,@rEmail
--end
--/*========================更新地址簿结束==============================*/ 
                                       


/*=========================记录订单生成日志开始==============================*/ 
exec XpProc_OrderOpLog_Add @orderid,@orderno,@membername,@memberid,'管理员','团购成交，管理员手动生成团购订单','团购成交，管理员手动生成团购订单',0,1
--如果使用了预付款要插入订单支付日志
if(@usedAdvPayment<>0)
exec XpProc_OrderOpLog_Add @orderid,@orderno,@membername,@memberid,'顾客','顾客预付款支付订单','顾客预付款支付订单',@status,1
/*=========================记录订单生成日志结束==============================*/  
select @errorflag=0,@errormsg=''
commit  
End Try
Begin Catch
--回滚事务
rollback
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1,@orderid=-1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
end

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PaymentOrder_Get]    脚本日期: 04/09/2012 18:27:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-10-16>
-- Description:	<获取订单可选支付方式>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PaymentOrder_Get]
@paytype int=null,--支付类型
@orderid int--订单ID
AS
BEGIN
select @paytype=isnull(@paytype,paytype) from orders where orderid=@orderid
--如果是在线支付类型
if isnull(@paytype,-1)=1
begin
declare @banknum int
select @banknum=count(1) from orderproduct p(nolock),pmtrule r(nolock) 
where p.orderid=@orderid and p.ruleid=r.ruleid and isnull(r.bankno,'-1')<>'-1'
if @banknum>0
begin
select PaymentID,[Name],Description
from Payment(nolock)
where InterfaceID=32 and status=1
end
else
begin
select PaymentID,[Name],Description
from Payment(nolock)
where PayType=@paytype and Status=1 
Order By Sort
end
end
else
begin
select PaymentID,[Name],Description
from Payment(nolock)
where PayType=@paytype and Status=1 
Order By Sort	
end
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PayOnLineGift_Send]    脚本日期: 04/09/2012 18:27:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Hakkas@qq.com>
-- Create date: <2012-03-30>
-- Description:	<在线支付送礼>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PayOnLineGift_Send]
	@orderNo varchar(50),--订单编号
	@money decimal(18,2),--支付金额
	@errorFlag int output
AS
BEGIN
select @errorFlag=1
begin try
	declare @paymenttype int,@supplierid int ,@orderid int,@ordertime datetime,@memberid int
	select @paymenttype=paymenttype,@supplierid=supplierid,@orderid=orderid ,@ordertime=ordertime,@memberid=memberid
	from orders(nolock) 
	where OrderNo=@orderno
	
	--查找满足订单在线支付赠品规则
	select r.ruleid,r.rulename,r.supplierid,r.bankno,t.goodsid,t.productid,t.limitednumber,@orderid as orderid,@orderno as orderno,@ordertime as ordertime,@memberid as memberid,g.memberprice,g.goodsname,g.goodsno,g.weight,p.ThumbnailImg,p.categoryid,p.brandid,p.PackingList
	into #r
	from pmtrule r(nolock),pmtgifts t(nolock),goods g(nolock),product p(nolock)
	where r.bankno=@paymenttype and r.basictype='orders' and r.subtype='paygift' and (getdate() between r.begintime and r.endtime) and t.ruleid=r.ruleid and t.balance>0 and @money>=r.minvalue and t.goodsid=g.goodsid and g.productid=p.productid
	select * from #r
	--计算赠礼的总数、总重量、总优惠金额
	declare @quantity int,@weight decimal(18,2),@lessmoney decimal(18,2)
	select @quantity=sum(limitednumber),@weight=sum(weight),@lessmoney=sum(memberprice*limitednumber) from #r
	if @quantity is not null--总数大于0才需要送礼
	begin
		begin tran
		--插入礼品
		insert into OrderProduct                                               
		(
		OrderID,OrderNo,ProductID,Quantity,MemberPrice,--1                                              
		UnitPrice,SubPrice,LessMoney,Remark, --2                                             
		ProductName,ProductNo,ThumbnailImg,CategoryID, --3                                             
		BrandID,GoodsID,UsedScore,Ptype,GiftScore,GiftGetType,  --4
		IsOfferInvoice,CouponValue,CouponGoodsMoney,AvgCouponMoney,IsNeedStowage,
		SupplierID,Stockout,MemberID,OrderTime,Score,PackingList 
		)  
		select 
		orderid,orderno,productid,limitednumber,memberprice,
		0 as unitprice,0 as subprice,memberprice,'('+rulename+')' as remark,
		goodsname,goodsno,ThumbnailImg,categoryid,
		brandid,goodsid,0 as usedscore,1 as ptype,0 as giftscore,0 as GiftGetType,
		0 as IsOfferInvoice,0 as CouponValue,0 as CouponGoodsMoney,0 as AvgCouponMoney,0 as IsNeedStowage,
		SupplierID,limitednumber as Stockout,memberid,ordertime,0 as score,PackingList
		from #r                                  
		--更新订单表头信息	
		update o set o.quantity=o.quantity+isnull(@quantity,0),o.weight=o.weight+isnull(@weight,0),o.lessmoney=o.lessmoney+isnull(@lessmoney,0)
		from orders o
		where o.orderid=@orderid
		--记录赠送记录
		insert into paymentgift(orderid,orderno,memberid,paymenttype,productid,goodsid,productname,quantity)
		select orderid,orderno,memberid,bankno,productid,goodsid,goodsname,limitednumber
		from #r
		--更新礼品剩余数量
		update t set balance=balance-r.limitednumber from pmtgifts t,#r r where t.ruleid=r.ruleid and t.productid=r.productid and t.goodsid=r.goodsid
		commit tran
	end
	select @errorFlag=0
	
end try
begin catch
	select @errorflag=1	
	declare @errormsg varchar(200)
	select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
	print @errormsg
	rollback tran
end catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Pdt_Insert]    脚本日期: 04/09/2012 18:27:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Hakkas>
-- Create date: <2011-04-12>
-- Description:	<创建商品>
-- Update History
/*
Version:V0.1
Author:hakkas@qq.com
Time:2011.05.13
Description:
1、增加了多规格商品的支持
1.1、增加参数：
@gprices varchar(500),--逗号分隔的货品价格组合
@gstocks varchar(500),--逗号分隔的货品库存组合
@gcodes varchar(500),--逗号分隔的货品商家编码组合
@props varchar(500),--规格ID列表
@propsDesc varchar(500),--规格字符列表
@propsname varchar(500),--规格名称列表
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Pdt_Insert] 
@ProductID int out,
@ProductGroup int = NULL,
@ProductName nvarchar(510),
@CategoryID int = NULL,
@ProductNo nvarchar(100) = NULL,
@BrandID int = NULL,
@BrandName nvarchar(100) = NULL,
@ShortDesc varchar(255) = NULL,
@Unit nvarchar(20) = NULL,
@Weight decimal(18, 2),
@MarketPrice decimal(18, 2),
@MemberPrice decimal(18, 2),
@Score int = NULL,
--@ThumbnailImg nvarchar(100) = NULL,
--@ProductImg nvarchar(100) = NULL,
@Description ntext = NULL,
@PackingList varchar(500) = NULL,
@AfterService varchar(1000) = NULL,
@Storage int = NULL,
@AarnNum int = NULL,
@IsForSale tinyint,
@IsBuyLimited tinyint,
@IsPackaged tinyint = NULL,
@PackageInfo nvarchar(3000) = NULL,
--@StartTime smalldatetime = NULL,
--@EndTime smalldatetime = NULL,
@AddTime datetime,
@Status int = NULL,
@Sort int = NULL,
@IsVirtual tinyint = NULL,
@CanReview tinyint = NULL,
@IsDiscount tinyint = NULL,
--@Img5 varchar(50) = NULL,
--@Hits int = NULL,
@MiniBuyNum int = NULL,
@Spec nvarchar(4000) = NULL,
@SpecDesc nvarchar(4000) = NULL,
@Properties ntext = NULL,
--@SaleNum int = NULL,
@Title nvarchar(400) = NULL,
@MetaKeywords varchar(200) = NULL,
@MetaDescription varchar(200) = NULL,
@Keyword nvarchar(400) = NULL,
@SupplierID int = NULL,
@UseScore int = NULL,
@P1 tinyint = NULL,
@P2 tinyint = NULL,
@P3 tinyint = NULL,
@P4 tinyint = NULL,
@P5 tinyint = NULL,
@P6 tinyint = NULL,
@P7 tinyint = NULL,
@P8 tinyint = NULL,
@P9 tinyint = NULL,
@P10 tinyint = NULL,
/*
@P11 tinyint = NULL,
@P12 tinyint = NULL,
@P13 tinyint = NULL,
@P14 tinyint = NULL,
@P15 tinyint = NULL,
@P16 tinyint = NULL,
@P17 tinyint = NULL,
@P18 tinyint = NULL,
@P19 tinyint = NULL,
@P20 tinyint = NULL,
@P21 tinyint = NULL,
@P22 tinyint = NULL,
@P23 tinyint = NULL,
@P24 tinyint = NULL,
@P25 tinyint = NULL,
@P26 tinyint = NULL,
@P27 tinyint = NULL,
@P28 tinyint = NULL,
@P29 tinyint = NULL,
@P30 tinyint = NULL,
*/
@CategoryNo varchar(20) = NULL,
@SubCategoryID varchar(20) = NULL,
@Price1 decimal(18, 2) = NULL,
@Price2 decimal(18, 2) = NULL,
@ImgDomain varchar(100) = NULL,
@IsDlvUnit tinyint = NULL,
@DlvUnit int = NULL,
@IsOfferInvoice tinyint = NULL,
@IsNeedStorage tinyint = NULL,
@addpic1 varchar(200),
@addpic2 varchar(200),
@addpic3 varchar(200),
@addpic4 varchar(200) = NULL,
@addpic5 varchar(200) = NULL,
@addpic6 varchar(200),

@gprices varchar(500),--逗号分隔的货品价格组合
@gstocks varchar(500),--逗号分隔的货品库存组合
@gcodes varchar(500),--逗号分隔的货品商家编码组合
@props varchar(500),--规格ID列表
@propsDesc varchar(8000),--规格字符列表
@propsname varchar(8000),--规格名称列表

@addFit varchar(1000)=NULL,--逗号分隔的待增加的配件ID
@delFit varchar(1000)=NULL,--逗号分隔的待删除的配件ID
@addRlt varchar(1000)=NULL,--逗号分隔的待增加的相关商品ID
@delRlt varchar(1000)=NULL,--逗号分隔的待删除的相关商品ID

@imgfolder varchar(20) out,--图片存放目录
@errorFlag int out,
@errorMsg varchar(200) out
AS
BEGIN
--根据分类编号获取分类ID
select @CategoryID=CategoryID from Category where CategoryNo=@CategoryNo
--插入商品基本资料
INSERT product(
ProductName, CategoryID, ProductNo, BrandID, BrandName, ShortDesc,Unit, --1
Weight, MarketPrice, MemberPrice, Score, Description, PackingList, --2
AfterService, Storage, AarnNum, IsForSale, IsBuyLimited, IsPackaged, PackageInfo,AddTime, Status, --3
Sort, IsVirtual, CanReview, IsDiscount, MiniBuyNum, Spec, SpecDesc, Properties, --4
Title, MetaKeywords, MetaDescription, Keyword, SupplierID, UseScore, --5
P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, --6
--ThumbnailImg, ProductImg, Img5, Hits,SaleNum,--7
--P11, P12, P13, P14, P15, P16, P17, P18, P19, P20, P21, P22, P23, P24, P25, P26, P27, P28, P29, P30,--8 
CategoryNo, SubCategoryID, Price1, Price2, ImgFolder, ImgDomain, IsDlvUnit, DlvUnit, IsOfferInvoice,IsNeedStorage,IsDel --9 
)
VALUES (
@ProductName, COALESCE(@CategoryID, (1)), COALESCE(@ProductNo, ''), COALESCE(@BrandID, (0)), COALESCE(@BrandName, ''), COALESCE(@ShortDesc, ''), --1
COALESCE(@Unit, ''), @Weight, @MarketPrice, @MemberPrice, COALESCE(@Score, (0)),COALESCE(@Description, ''), COALESCE(@PackingList, ''), --2
COALESCE(@AfterService, ''), COALESCE(@Storage, (0)), COALESCE(@AarnNum, (0)), @IsForSale, @IsBuyLimited, COALESCE(@IsPackaged, (0)), COALESCE(@PackageInfo, ''),@AddTime, COALESCE(@Status, (0)), --3
COALESCE(@Sort, (0)), COALESCE(@IsVirtual, (0)), COALESCE(@CanReview, (1)), COALESCE(@IsDiscount, (1)), COALESCE(@MiniBuyNum, (1)), COALESCE(@Spec, ''), COALESCE(@SpecDesc, ''), COALESCE(@Properties, ''), --4
COALESCE(@Title, ''), COALESCE(@MetaKeywords, ''), COALESCE(@MetaDescription, ''), COALESCE(@Keyword, ''), COALESCE(@SupplierID, (0)), COALESCE(@UseScore, (0)), --5
COALESCE(@P1, (0)), COALESCE(@P2, (0)), COALESCE(@P3, (0)), COALESCE(@P4, (0)), COALESCE(@P5, (0)), COALESCE(@P6, (0)), COALESCE(@P7, (0)), COALESCE(@P8, (0)), COALESCE(@P9, (0)), COALESCE(@P10, (0)), --6
--COALESCE(@ThumbnailImg, 'nopic.gif'), COALESCE(@ProductImg, ''),  COALESCE(@Img5, ''), COALESCE(@Hits, (0)),COALESCE(@SaleNum, (0)), 
--COALESCE(@P11, (0)), COALESCE(@P12, (0)), COALESCE(@P13, (0)), COALESCE(@P14, (0)), COALESCE(@P15, (0)), COALESCE(@P16, (0)), COALESCE(@P17, (0)), COALESCE(@P18, (0)), COALESCE(@P19, (0)), COALESCE(@P20, (0)), COALESCE(@P21, (0)), COALESCE(@P22, (0)), COALESCE(@P23, (0)), COALESCE(@P24, (0)), COALESCE(@P25, (0)), COALESCE(@P26, (0)), COALESCE(@P27, (0)), COALESCE(@P28, (0)), COALESCE(@P29, (0)), COALESCE(@P30, (0)), --7
@CategoryNo, @SubCategoryID, @Price1, @Price2, @imgfolder, @ImgDomain, @IsDlvUnit, @DlvUnit, @IsOfferInvoice,COALESCE(@IsNeedStorage, (1)),0 --8
)
select @ProductID=@@IDENTITY

--计算图片存放目录，商品ID除以1000取余为第一级目录，除以100取余为第二级目录
declare @folder1 varchar(10),@folder2 varchar(10)
select @folder1=convert(varchar(10),@ProductID%1000),@folder2=convert(varchar(10),@ProductID%100)
select @imgfolder=@folder1+'/'+@folder2+'/'
select * into #p1 from dbo.SplitToTable_Func(@addpic1,'|')
select * into #p2 from dbo.SplitToTable_Func(@addpic2,'|')
select * into #p3 from dbo.SplitToTable_Func(@addpic3,'|')
select * into #p4 from dbo.SplitToTable_Func(@addpic4,'|')
select * into #p5 from dbo.SplitToTable_Func(@addpic5,'|')
select * into #p6 from dbo.SplitToTable_Func(@addpic6,'|')

select pid=@ProductID,p1.value as img1,p2.value as img2,p3.value as img3,p4.value as img4,p5.value as img5,p6.value as img6,imgfolder=@imgfolder,sid=@SupplierID,isdel=0,status=1,p1.id as sort 
into #p 
from #p1 p1,#p2 p2,#p3 p3,#p4 p4,#p5 p5,#p6 p6 
where p1.id=p2.id and p1.id=p3.id and p1.id=p4.id and p1.id=p5.id and p1.id=p6.id

--select * from #p
--插入商品图片
insert into pdtimg(pid,img1,img2,img3,img4,img5,img6,imgfolder,sid,isdel,status,sort) select * from #p

--插入货品到Goods表开始
--declare @productid int,@productno varchar(50),@marketprice decimal(18,2),@weight decimal(18,2),@supplierid int,@gprices varchar(500),@gstocks varchar(500),@gcodes varchar(500)
--select @productid=10001,@productno='A123',@marketprice=150,@weight=2,@supplierid=0,@gprices='100,110,120',@gstocks='10,10,10',@gcodes=''
--判断有无多规格
if(@gprices<>'' and @gstocks<>'')
begin
--有多规格的情况
select * into #g1 from SplitToTable_Func(@gprices,',')
select * into #g2 from SplitToTable_Func(@gstocks,',')
select * into #g3 from SplitToTable_Func(@gcodes,',')
select * into #g4 from SplitToTable_Func(@props,',')
select * into #g5 from SplitToTable_Func(@propsdesc,',')
select * into #g6 from SplitToTable_Func(@propsname,',')
select productid=@ProductID,goodsno=case when isnull(g3.value,'')='' then @ProductNo else g3.value end,marketprice=@MarketPrice,memberprice=g1.value,weight=@Weight,Score=@Score,storage=g2.value,goodsname=@productname+' '+g6.value,supplierid=@SupplierID,props=g4.value,propsdesc=g5.value
into #g 
from #g1 g1
left join #g2 g2 on g1.id=g2.id
left join #g3 g3 on g1.id=g3.id
left join #g4 g4 on g1.id=g4.id
left join #g5 g5 on g1.id=g5.id
left join #g6 g6 on g1.id=g6.id
/*
select * from #g1
select * from #g2
select * from #g3
select * from #g
drop table #g1
drop table #g2
drop table #g3
drop table #g
*/
insert into goods(productid,goodsno,marketprice,memberprice,weight,score,storage,goodsname,supplierid,props,propsdesc) select * from #g
end
else
begin
--没有多规格的情况
insert into goods (
productid,goodsno,marketprice,memberprice,weight,score,storage,goodsname,supplierid
)values(
@productid,@productno,@marketprice,@memberprice,@weight,@score,@storage,@productname,@supplierid
)
end

--添加和删除配件
if isnull(@delFit,'')<>''
begin
select * into #f1 from dbo.SplitToTable_Func(@delFit,',')
delete f from Fitting f,#f1 f1 where r.productid=@productid and f.FitID=f1.value
end

if isnull(@addFit,'')<>''
begin
select id as sort,ProductID=@ProductID,value as FitID into #f2 from dbo.SplitToTable_Func(@addFit,',')
insert into Fitting(ProductID,FitID,Sort) select ProductID,FitID,Sort from #f2
end

--添加和删除相关商品
if isnull(@delRlt,'')<>''
begin
select * into #r1 from dbo.SplitToTable_Func(@delRlt,',')
delete r from RltPdts r,#r1 r1 where r.productid=@productid and r.RltPdtID=r1.value
end

if isnull(@addRlt,'')<>''
begin
select id as sort,ProductID=@productid,value as RltPdtID into #r2 from dbo.SplitToTable_Func(@addRlt,',')
insert into RltPdts(ProductID,RltPdtID,Sort) select productid,RltPdtID,sort from #r2
end

--构造SkuMap并更新到商品表
declare @skumap varchar(8000),@propid varchar(50),@goodsid int,@goodsprice decimal(18,2),@goodsstock int,@goodsno varchar(50)
--定义遍历当前商品的不同规格的货品的游标
declare goods_items_cursor cursor for                                                    
select goodsid,goodsno,memberprice,storage,props
from goods
where productid=@ProductID
order by goodsid asc
select @skumap='{'
--遍历游标
open goods_items_cursor                                                    
fetch next from goods_items_cursor into 
@goodsid,@goodsno,@goodsprice,@goodsstock,@propid
while @@fetch_status = 0                        
begin 
select @skumap=@skumap+'"'+isnull(@propid,'0:0;0:0')+'":{"skuId":"'+cast(@goodsid as varchar(50))+'","price":"'+cast(@goodsprice as varchar(50))+'","stock":"'+cast(@goodsstock as varchar(50))+'","code":"'+@goodsno+'"},'
fetch next from goods_items_cursor into 
@goodsid,@goodsno,@goodsprice,@goodsstock,@propid
end
--遍历结束
close goods_items_cursor                                                    
deallocate goods_items_cursor 

--去掉最后一个逗号
if len(@skumap)>1
select @skumap=substring(@skumap,1,len(@skumap)-1)
select @skumap=@skumap+'}'

--更新商品表的缩略图,图片目录,SkuMap
declare @pic3 varchar(20),@pic5 varchar(20),@pic6 varchar(20)
select @pic3='none.gif',@pic5='none.gif',@pic6='none.gif'
select top 1 @pic3=img3,@pic5=img5,@pic6=img6 from #p
update product set ProductGroup=@ProductID,Sort=@ProductID,ThumbnailImg=@pic3,ProductImg=@pic6,Img5=@pic5,ImgFolder=@imgfolder,SkuMap=@skumap where productid=@ProductID

select @errorFlag=0,@errorMsg=''
END

/*
select * into #p1 from dbo.SplitToTable_Func('1_1.jpg|2_1.jpg|3_1.jpg|4_1.jpg','|')
select * into #p2 from dbo.SplitToTable_Func('1_2.jpg|2_2.jpg|3_2.jpg|4_2.jpg','|')
select * into #p3 from dbo.SplitToTable_Func('1_3.jpg|2_3.jpg|3_3.jpg|4_3.jpg','|')
select * into #p6 from dbo.SplitToTable_Func('1_4.jpg|2_4.jpg|3_4.jpg|4_4.jpg','|')
declare @pid int
select @pid=1
select pid=@pid,p1.value as img1,p2.value as img2,p3.value as img3,p6.value as img6,p1.id as sort into #p from #p1 p1,#p2 p2,#p3 p3,#p6 p6 where p1.id=p2.id and p1.id=p3.id and p1.id=p6.id
select * from #p
--insert into pdtimg(pid,img1,img2,img3,img6) select * from #p
select top 1 img3,img6 from #p
drop table #p
drop table #p1
drop table #p2
drop table #p3
drop table #p6
*/






















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Pdt_Update]    脚本日期: 04/09/2012 18:27:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Hakkas>
-- Create date: <2011-04-18>
-- Description:	<更新商品>
-- Update History
/*
Version:V0.1
Author:hakkas@qq.com
Time:2011.05.13
Description:
1、增加了多规格商品的支持
1.1、增加参数：
@gids varchar(500),--逗号分隔的货品ID组合
@gprices varchar(500),--逗号分隔的货品价格组合
@gstocks varchar(500),--逗号分隔的货品库存组合
@gcodes varchar(500),--逗号分隔的货品商家编码组合
@props varchar(500),--规格ID列表
@propsDesc varchar(500),--规格字符列表
@propsname varchar(500),--规格名称列表
*/
-- =============================================
CREATE PROC [dbo].[XpProc_Pdt_Update]
	@ProductID int,
	@ProductGroup int = NULL,
	@ProductName nvarchar(510),
	@CategoryID int,
	@ProductNo nvarchar(100),
	@BrandID int,
	@BrandName nvarchar(100) = NULL,
	@ShortDesc varchar(255),
	@Unit nvarchar(20) = NULL,
	@Weight decimal(18, 2),
	@MarketPrice decimal(18, 2),
	@MemberPrice decimal(18, 2),
	@Score int,
	--@ThumbnailImg nvarchar(100) = NULL,
	--@ProductImg nvarchar(100) = NULL,
	@Description ntext,
	@PackingList varchar(500) = NULL,
	@AfterService varchar(1000) = NULL,
	@Storage int,
	@AarnNum int,
	@IsForSale tinyint,
	@IsBuyLimited tinyint,
	@IsPackaged tinyint,
	@PackageInfo nvarchar(3000) = NULL,
	--@StartTime smalldatetime = NULL,
	--@EndTime smalldatetime = NULL,
	@UpdateTime datetime = NULL,
	@Status int,
	--@Sort int,
	@IsVirtual tinyint,
	@CanReview tinyint,
	@IsDiscount tinyint,
	--@Img5 nvarchar(50) = NULL,
	--@Hits int,
	@MiniBuyNum int=null,
	@Spec nvarchar(4000) = NULL,
	@SpecDesc nvarchar(4000) = NULL,
	@Properties ntext = NULL,
	--@SaleNum int,
	@Title nvarchar(400) = NULL,
	@MetaKeywords varchar(200) = NULL,
	@MetaDescription varchar(200) = NULL,
	@Keyword nvarchar(400) = NULL,
	@SupplierID int,
	@UseScore int,
	@P1 tinyint,
	@P2 tinyint,
	@P3 tinyint,
	@P4 tinyint,
	@P5 tinyint,
	@P6 tinyint,
	@P7 tinyint,
	@P8 tinyint,
	@P9 tinyint,
	@P10 tinyint,
/*
	@P11 tinyint,
	@P12 tinyint,
	@P13 tinyint,
	@P14 tinyint,
	@P15 tinyint,
	@P16 tinyint,
	@P17 tinyint,
	@P18 tinyint,
	@P19 tinyint,
	@P20 tinyint,
	@P21 tinyint,
	@P22 tinyint,
	@P23 tinyint,
	@P24 tinyint,
	@P25 tinyint,
	@P26 tinyint,
	@P27 tinyint,
	@P28 tinyint,
	@P29 tinyint,
	@P30 tinyint,
*/
	@CategoryNo varchar(20) = NULL,
	@SubCategoryID varchar(20) = NULL,
	--@Price1 decimal(18, 2) = NULL,
	--@Price2 decimal(18, 2) = NULL,
	--@ImgDomain varchar(100) = NULL,
	@IsDlvUnit tinyint = NULL,
	@DlvUnit int = NULL,
	@IsOfferInvoice tinyint = NULL,
	@IsNeedStorage tinyint = NULL,
	@delPic varchar(200),
	@addPic1 varchar(200),
	@addPic2 varchar(200),
	@addPic3 varchar(200),
	@addPic4 varchar(200) = NULL,
	@addPic5 varchar(200) = NULL,
	@addPic6 varchar(200),
	@addPos varchar(20),
	@updatePic varchar(200),
	@updatePos varchar(20),

	@gids varchar(500),--逗号分隔的货品ID组合
	@gprices varchar(500),--逗号分隔的货品价格组合
	@gstocks varchar(500),--逗号分隔的货品库存组合
	@gcodes varchar(500),--逗号分隔的货品商家编码组合
	@props varchar(500),--规格ID列表
	@propsDesc varchar(8000),--规格字符列表
	@propsname varchar(8000),--规格名称列表

	@addFit varchar(1000)=NULL,--逗号分隔的待增加的配件ID
	@delFit varchar(1000)=NULL,--逗号分隔的待删除的配件ID
	@addRlt varchar(1000)=NULL,--逗号分隔的待增加的相关商品ID
	@delRlt varchar(1000)=NULL,--逗号分隔的待删除的相关商品ID

	@imgfolder varchar(20) out,--图片存放目录
	@errorFlag int out,
	@errorMsg varchar(200) out
AS
BEGIN
select @CategoryID=CategoryID from Category where CategoryNo=@CategoryNo
select @imgfolder=isnull(ImgFolder,'') from product where ProductID=@ProductID

--更新商品资料
UPDATE	Product
SET	ProductName = @ProductName,
	CategoryID = COALESCE(@CategoryID, (1)),
	ProductNo = COALESCE(@ProductNo, ''),
	BrandID = COALESCE(@BrandID, (0)),
	BrandName = COALESCE(@BrandName, ''),
	ShortDesc = COALESCE(@ShortDesc, ''),
	Unit = COALESCE(@Unit, ''),
	Weight = @Weight,
	MarketPrice = @MarketPrice,
	MemberPrice = @MemberPrice,
	Score = COALESCE(@Score, (0)),
	--ThumbnailImg = COALESCE(@ThumbnailImg, 'nopic.gif'),
	--ProductImg = COALESCE(@ProductImg, ''),
	Description = COALESCE(@Description, ''),
	PackingList = COALESCE(@PackingList, ''),
	AfterService = COALESCE(@AfterService, ''),
	Storage = COALESCE(@Storage, (0)),
	AarnNum = COALESCE(@AarnNum, (0)),
	IsForSale = @IsForSale,
	IsBuyLimited = @IsBuyLimited,
	IsPackaged = COALESCE(@IsPackaged, (0)),
	PackageInfo = COALESCE(@PackageInfo, ''),
	--StartTime = @StartTime,
	--EndTime = @EndTime,
	--UpdateTime = @UpdateTime,
	--Status = COALESCE(@Status, (0)),
	--Sort = COALESCE(@Sort, (0)),
	IsVirtual = COALESCE(@IsVirtual, (0)),
	CanReview = COALESCE(@CanReview, (1)),
	IsDiscount = COALESCE(@IsDiscount, (1)),
	--Img5 = COALESCE(@Img5, ''),
	--Hits = COALESCE(@Hits, (0)),
	MiniBuyNum = COALESCE(@MiniBuyNum, (1)),
	Spec = COALESCE(@Spec, ''),
	SpecDesc = COALESCE(@SpecDesc, ''),
	Properties = COALESCE(@Properties, ''),
	--SaleNum = COALESCE(@SaleNum, (0)),
	Title = COALESCE(@Title, ''),
	MetaKeywords = COALESCE(@MetaKeywords, ''),
	MetaDescription = COALESCE(@MetaDescription, ''),
	Keyword = COALESCE(@Keyword, ''),
	SupplierID = COALESCE(@SupplierID, (0)),
	UseScore = COALESCE(@UseScore, (0)),
	P1 = COALESCE(@P1, (0)),
	P2 = COALESCE(@P2, (0)),
	P3 = COALESCE(@P3, (0)),
	P4 = COALESCE(@P4, (0)),
	P5 = COALESCE(@P5, (0)),
	P6 = COALESCE(@P6, (0)),
	P7 = COALESCE(@P7, (0)),
	P8 = COALESCE(@P8, (0)),
	P9 = COALESCE(@P9, (0)),
	P10 = COALESCE(@P10, (0)),
/*
	P11 = COALESCE(@P11, (0)),
	P12 = COALESCE(@P12, (0)),
	P13 = COALESCE(@P13, (0)),
	P14 = COALESCE(@P14, (0)),
	P15 = COALESCE(@P15, (0)),
	P16 = COALESCE(@P16, (0)),
	P17 = COALESCE(@P17, (0)),
	P18 = COALESCE(@P18, (0)),
	P19 = COALESCE(@P19, (0)),
	P20 = COALESCE(@P20, (0)),
	P21 = COALESCE(@P21, (0)),
	P22 = COALESCE(@P22, (0)),
	P23 = COALESCE(@P23, (0)),
	P24 = COALESCE(@P24, (0)),
	P25 = COALESCE(@P25, (0)),
	P26 = COALESCE(@P26, (0)),
	P27 = COALESCE(@P27, (0)),
	P28 = COALESCE(@P28, (0)),
	P29 = COALESCE(@P29, (0)),
	P30 = COALESCE(@P30, (0)),
*/
	CategoryNo = @CategoryNo,
	SubCategoryID = @SubCategoryID,
	--Price1 = @Price1,
	--Price2 = @Price2,
	--ImgFolder = @ImgFolder,
	--ImgDomain = @ImgDomain,
	IsDlvUnit = @IsDlvUnit,
	DlvUnit = @DlvUnit,
	IsOfferInvoice = @IsOfferInvoice,
	IsNeedStorage = @IsNeedStorage
WHERE 	ProductID = @ProductID

--删除图片
select * into #d from dbo.SplitToTable_Func(@delpic,'|')
delete p
from PdtImg p,#d d
where p.img1=d.value and p.sid=@SupplierID

--更改原有图片的排序
if(@updatePic<>'')
begin
select * into #u from dbo.SplitToTable_Func(@updatePic,'|')
select * into #up from dbo.SplitToTable_Func(@updatePos,'|')
select u.value as img1,up.value as sort into #uup from #u u,#up up where u.id=up.id
update p 
set p.sort=uup.sort
from PdtImg p,#uup uup
where p.img1=uup.img1 and p.sid=@SupplierID
end


--添加图片
--先判断之前的图片存放目录是否为空，如果为空则重新计算图片存放路径
if(@imgfolder='')
begin
--计算图片存放目录，商品ID除以1000取余为第一级目录，除以100取余为第二级目录
declare @folder1 varchar(10),@folder2 varchar(10)
select @folder1=convert(varchar(10),@ProductID%1000),@folder2=convert(varchar(10),@ProductID%100)
select @imgfolder=@folder1+'/'+@folder2+'/'
end

select * into #p1 from dbo.SplitToTable_Func(@addpic1,'|')
select * into #p2 from dbo.SplitToTable_Func(@addpic2,'|')
select * into #p3 from dbo.SplitToTable_Func(@addpic3,'|')
select * into #p4 from dbo.SplitToTable_Func(@addpic4,'|')
select * into #p5 from dbo.SplitToTable_Func(@addpic5,'|')
select * into #p6 from dbo.SplitToTable_Func(@addpic6,'|')
select * into #pos from dbo.SplitToTable_Func(@addPos,'|')

select pid=@ProductID,p1.value as img1,p2.value as img2,p3.value as img3,p4.value as img4,p5.value as img5,p6.value as img6,imgfolder=@imgfolder,sid=@SupplierID,isdel=0,status=1,p1.id as sort 
into #p 
from #p1 p1,#p2 p2,#p3 p3,#p4 p4,#p5 p5,#p6 p6 
where p1.id=p2.id and p1.id=p3.id and p1.id=p4.id and p1.id=p5.id and p1.id=p6.id

--select * from #p
--插入商品图片
insert into pdtimg(pid,img1,img2,img3,img4,img5,img6,imgfolder,sid,isdel,status,sort) select * from #p

--更新商品表的缩略图，图片目录
declare @pic3 varchar(20),@pic5 varchar(20),@pic6 varchar(20)
select @pic3='none.gif',@pic5='none.gif',@pic6='none.gif'
--select top 1 @pic3=img3,@pic5=img5,@pic6=img6 from #p
select top 1 @pic3=img3,@pic5=img5,@pic6=img6 from pdtimg where pid=@productid order by sort
update product set ThumbnailImg=@pic3,ProductImg=@pic6,Img5=@pic5,ImgFolder=@imgfolder where productid=@ProductID


--更新货品资料
--declare @productid int,@productno varchar(50),@productname varchar(100),@marketprice decimal(18,2),@weight decimal(18,2),@gids varchar(500),@gprices varchar(500),@gstocks varchar(500),@gcodes varchar(500),@props varchar(500),@propsdesc varchar(500),@propsname varchar(500)
--select @productid=567,@productname='马克华菲男装新品时尚圆领短袖T恤',@productno='A123',@marketprice=150,@weight=2,@gids=',,',@gprices='100,110,120',@gstocks='10,10,10',@gcodes='',@props='1:1;2:5,1:1;2:6,1:2;2:5',@propsdesc='颜色:红色;尺寸:XL,颜色:红色;尺寸:L,颜色:蓝色;尺寸:XL',@propsname='红色 XL,红色 L,蓝色 XL'
--判断有无多规格
if(@gprices<>'' and @gstocks<>'')
begin
--有多规格的情况
print('有多规格的情况')
select * into #g0 from SplitToTable_Func(@gids,',')
select * into #g1 from SplitToTable_Func(@gprices,',')
select * into #g2 from SplitToTable_Func(@gstocks,',')
select * into #g3 from SplitToTable_Func(@gcodes,',')
select * into #g4 from SplitToTable_Func(@props,',')
select * into #g5 from SplitToTable_Func(@propsdesc,',')
select * into #g6 from SplitToTable_Func(@propsname,',')
select goodsid=isnull(g0.value,''),productid=@ProductID,goodsno=case when isnull(g3.value,'')='' then @ProductNo else g3.value end,marketprice=@MarketPrice,memberprice=g1.value,weight=@Weight,Score=@Score,storage=g2.value,goodsname=@productname+' '+g6.value,supplierid=@supplierid,props=g4.value,propsdesc=g5.value 
into #g 
from #g1 g1
left join #g0 g0 on g1.id=g0.id
left join #g2 g2 on g1.id=g2.id
left join #g3 g3 on g1.id=g3.id
left join #g4 g4 on g1.id=g4.id
left join #g5 g5 on g1.id=g5.id
left join #g6 g6 on g1.id=g6.id

--删除不存在的货品
delete from goods where goods.productid=@productid and goods.goodsid not in (select goodsid from #g where #g.goodsid<>'')

--更新货品
update g 
set g.goodsno=gt.goodsno,g.marketprice=gt.marketprice,g.memberprice=gt.memberprice,g.weight=gt.weight,g.score=gt.score,g.storage=gt.storage,g.goodsname=gt.goodsname,g.props=gt.props,g.propsdesc=gt.propsdesc
from goods g(nolock),#g gt
where g.goodsid=gt.goodsid

--插入新货品
insert into goods(productid,goodsno,marketprice,memberprice,weight,score,storage,goodsname,supplierid,props,propsdesc) select productid,goodsno,marketprice,memberprice,weight,score,storage,goodsname,supplierid,props,propsdesc from #g where #g.goodsid=''
/*
select * from #g0
select * from #g1
select * from #g2
select * from #g3
select * from #g4
select * from #g5
select * from #g6
select * from #g
select * from goods g(nolock) where g.productid=@productid and g.goodsid not in(select goodsid from #g where #g.goodsid<>'')
drop table #g0
drop table #g1
drop table #g2
drop table #g3
drop table #g4
drop table #g5
drop table #g6
drop table #g
*/
end
else
begin
--没有多规格的情况
print('没有多规格的情况')
update top (1) goods
set goodsno=@productno,marketprice=@marketprice,memberprice=@memberprice,weight=@weight,score=@score,storage=@storage,goodsname=@productname,props=null,propsdesc=null
where productid=@productid 

delete from goods where isnull(props,'')<>'' and isnull(propsdesc,'')<>'' and productid=@productid
end

--添加和删除配件
if isnull(@delFit,'')<>''
begin
select * into #f1 from dbo.SplitToTable_Func(@delFit,',')
delete f from Fitting f,#f1 f1 where f.productid=@productid and f.FitID=f1.value
end

if isnull(@addFit,'')<>''
begin
select id as sort,ProductID=@ProductID,value as FitID into #f2 from dbo.SplitToTable_Func(@addFit,',')
insert into Fitting(ProductID,FitID,Sort) select ProductID,FitID,Sort from #f2
end

--添加和删除相关商品
if isnull(@delRlt,'')<>''
begin
select * into #r1 from dbo.SplitToTable_Func(@delRlt,',')
delete r from RltPdts r,#r1 r1 where r.productid=@productid and r.RltPdtID=r1.value
end

if isnull(@addRlt,'')<>''
begin
select id as sort,ProductID=@productid,value as RltPdtID into #r2 from dbo.SplitToTable_Func(@addRlt,',')
insert into RltPdts(ProductID,RltPdtID,Sort) select productid,RltPdtID,sort from #r2
end

--构造SkuMap并更新到商品表
declare @skumap varchar(8000),@propid varchar(50),@goodsid int,@goodsprice decimal(18,2),@goodsstock int,@goodsno varchar(50)
--定义遍历当前商品的不同规格的货品的游标
declare goods_items_cursor cursor for                                                    
select goodsid,goodsno,memberprice,storage,props
from goods
where productid=@ProductID
order by goodsid asc
select @skumap='{'
--遍历游标
open goods_items_cursor                                                    
fetch next from goods_items_cursor into 
@goodsid,@goodsno,@goodsprice,@goodsstock,@propid
while @@fetch_status = 0                        
begin 
select @skumap=@skumap+'"'+isnull(@propid,'0:0;0:0')+'":{"skuId":"'+cast(@goodsid as varchar(50))+'","price":"'+cast(@goodsprice as varchar(50))+'","stock":"'+cast(@goodsstock as varchar(50))+'","code":"'+@goodsno+'"},'
fetch next from goods_items_cursor into 
@goodsid,@goodsno,@goodsprice,@goodsstock,@propid
end
--遍历结束
close goods_items_cursor                                                    
deallocate goods_items_cursor 

--去掉最后一个逗号
if len(@skumap)>1
select @skumap=substring(@skumap,1,len(@skumap)-1)
select @skumap=@skumap+'}'
update product set SkuMap=@skumap where ProductID=@ProductID

select @errorFlag=0,@errorMsg=''
END

















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtAsk_Get]    脚本日期: 04/09/2012 18:28:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<liwenhai>
-- Create date: <2012-02-02>
-- Description:	<用于前台，商家后台，管理后台查找商品咨询>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtAsk_Get]
@pageno int=1,
@PageSize int=30,
@sortType varchar(50)=null,
--搜索条件
@searchType int=null,
@keyword varchar(50)=null,
@status int=null,--是否已回复，0是未回复 1是已回复 -1是不限
@isHide int=null,--是否隐藏，0是未隐藏 1是已隐藏 -1是不限
@productid int=null,--产品ID
@productName varchar(50)=null,--产品名称
@productNo varchar(200)=null,--产品编号
@membername varchar(50)=null,--咨询人名称
@startAddTime varchar(50)=null,--咨询添加时间
@endAddTime varchar(50)=null,
@startReplyTime varchar(50)=null,--咨询回复时间
@endReplyTime varchar(50)=null,
@supplierid int=null,--是否搜索运营商自已的商品咨询，-2查找所有的商家的，-1查找非自营 0查找自营商品 其它值就是查找对应的商家商品咨询
@memberid int=null,--会员ID 前台查找需要
@isBackGround bit=null,--是前台还是后台，查找商品咨询
@totalcount int =null output,
@totalpage int=null output,
@errorFlag int=null output,
@errorMsg varchar(200)=null output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0
Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000),@from nvarchar(4000)
--构造搜索条件
--要查找的表,前台跟后台要联的表是不同的
--分页排序
declare @sort varchar(50)
select @sort= CASE @sortType WHEN 'ProductAskID' THEN 'ORDER BY ProductAskID DESC' WHEN 'AddTime' THEN 'ORDER BY AddTime DESC' else 'ORDER BY ProductAskID DESC' end
if @isBackGround=1
begin
	select @from=' ProductAsk pa,Product p' 
	select @where=' pa.Productid=p.Productid'
	--构造后台的查询条件
	if isnull(@searchtype,-1)<>-1
	begin
	select @where= CASE @searchtype
	WHEN 0 THEN @where+' AND (p.ProductName Like ''%' + @keyword + '%'' or p.ProductNo Like ''%' + @keyword + '%'' or pa.MemberName Like ''%' + @keyword + '%'')'
	WHEN 1 THEN @where+' AND p.ProductName like ''%' + @keyword + '%'''
	WHEN 2 THEN @where+' AND p.ProductNo like ''%' + @keyword + '%'''
	WHEN 3 THEN @where+' AND pa.ProductID like ''%' + @keyword + '%'''
	WHEN 4 THEN @where+' AND pa.MemberName like ''%' + @keyword + '%'''
	END
	end
	if isnull(@productid,-1)<>-1
	select @where=@where+' AND pa.ProductID='+cast(@productid as varchar(20))
	if isnull(@productname,'')<>''
	select @where=@where+' AND p.ProductName like ''%' + @productname + '%'''
	if isnull(@productid,-1)<>-1
	select @where=@where+' AND pa.Productid like ''%' + cast(@productid as varchar(20)) + '%'''
	if isnull(@membername,'')<>''
	select @where=@where+' AND pa.Membername like ''%' + @membername + '%'''
	if isnull(@status,-1)<>-1
	select @where=@where+' AND pa.status= '+cast(@status as varchar(2))
	if isnull(@isHide,-1)<>-1
	select @where=@where+' AND isHide= '+cast(@isHide as varchar(2))
	if isnull(@supplierid,-2)<>-2
	begin
	select @where=CASE @supplierid
	WHEN -1 THEN @where+' AND pa.SupplierID <>0'
	WHEN 0 THEN @where+'  AND pa.SupplierID =0'
	Else @where+' AND pa.SupplierID ='+cast(@supplierid as varchar(20))
	END
	end
	if isnull(@startAddTime,'')<>''
	select @where=@where+' and pa.AddTime>=''' + @startAddTime + ''''
	if isnull(@endAddTime,'')<>''
	select @where=@where+' and pa.AddTime<=''' + @endAddTime + ' 23:59:59.999'+''''
	if isnull(@startReplyTime,'')<>''
	select @where=@where+' and pa.replytime>=''' + @startReplyTime + ''''
	if isnull(@endReplyTime,'')<>''
	select @where=@where+' and pa.replytime<=''' + @endReplyTime + ' 23:59:59.999'+''''
	--后台商品咨询分页
	select @sqlstr='select *from(select ProductAskID,pa.ProductID,pa.MemberID,Body,pa.AddTime,Reply,AdminName,YesNum,NotNum,pa.Status,MemberName,IsHide,ProductName,
	Row_number() over('+@sort+') as rowno
	from '+@from+'
	where ' + @where + ') as pa
	where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
	--insert log (content)values(@sqlstr)
end
else
begin
	select @from=' ProductAsk pa,Member m,MemberGroup mg'
	select @where=' pa.memberid=m.memberid and m.groupid=mg.membergroupid'
	--前台条件
	if isnull(@memberid,-1)<>-1
	select @where=@where+' and (ishide=0 or(ishide=1 and pa.memberid='+cast(@memberid as varchar(20))+'))and productid='+cast(@productid as varchar(20))
	else
	select @where=@where+' and ishide=0 and productid='+cast(@productid as varchar(20))
	--前台商品咨询分页
	select @sqlstr='select *from(select ProductAskID,pa.MemberID,Body,AddTime,Reply,ReplyTime,YesNum,NotNum,pa.Status,pa.MemberName,m.GroupID,GroupName,Logo,
	Row_number() over('+@sort+') as rowno
	from '+@from+'
	where ' + @where + ') as pa
	where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
	insert log (content)values(@sqlstr)
end
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over('+@sort+') as rowno 
from '+@from+'
where ' + @where + ') as p)'

Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtAsk_Select]    脚本日期: 04/09/2012 18:28:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<用于商家后台，查询出商家问答>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtAsk_Select]
@aid int
AS
BEGIN
select productask.*,product.productname from productask(nolock) ,product(nolock) where productask.productid=product.productid and productaskid=@aid
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtAsk_Update]    脚本日期: 04/09/2012 18:28:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<用于更新ProductAsk表中纪录的 Reply, ReplyTime ,Status 或IsHide等字段的值>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtAsk_Update]
@paid int=null,--要更新的ProductAskID
@operatorid int=null,--回复人ID
@realname varchar(200)=null,--回复人真实姓名
@reply varchar(1024)=null,--回复内容
@status int=null ,--回复状态，0未回复 1已回复
@ishide bit=null,--商品咨询是否在前台可见，0是可见，1是隐藏但是提问人可见
@isonlychangehide bit,--是否只是改变ishide的值
@errorflag int output,--操作结果标识，0成功 1失败
@errorMsg varchar(200) output --操作结果提示
AS
BEGIN
select @errorflag=1
select @errormsg='操作失败'
if @isonlychangehide=1 --只是改变IsHide为公开或隐藏
begin
update productask set ishide=ishide^1 where productaskid=@paid
if @@rowcount>0
begin
select @errorflag=0
select @errormsg='状态更新成功'
end
else
begin
select @errorflag=0
select @errormsg='商品咨询不存在'
end
end
else--否则的话，是回复会员的提问
begin
UPDATE ProductAsk Set Reply =@reply,replytime=getDate(),operator=@operatorid,AdminName=@realname,Status =@status,isHide =@ishide Where ProductAskID =@paid
if @@rowcount>0
begin
select @errorflag=0
select @errormsg='商品咨询回复成功'
end
else
begin
select @errorflag=0
select @errormsg='商品咨询不存在'
end
end
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtCityName_Update]    脚本日期: 04/09/2012 18:28:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2012-03-29>
-- Description:	<批量更新商品限制城市名称>
-- =============================================
CREATE procedure [dbo].[XpProc_PdtCityName_Update]
@pid int=null
as
begin
	declare @productid int,@cityname varchar(200)
	if @pid is null
	begin
		declare products_items_cursor cursor for select productid from pdtcity group by productid
		open products_items_cursor
		fetch next from products_items_cursor into @productid
		while @@fetch_status=0
		begin
			select @cityname='' 
			select @cityname=@cityname+'、'+[name] from pdtcity c,shippingarea a where c.city=a.shippingareaid and c.productid=@productid
			select @cityname=stuff(@cityname,1,1,'')
			update product set shortdesc='(仅限'+@cityname+'购买)' where productid=@productid
			fetch next from products_items_cursor into @productid
		end                                           
		close products_items_cursor   
		deallocate products_items_cursor
	end
	else
	begin
		select @cityname='',@productid=@pid
		select @cityname=@cityname+'、'+[name] from pdtcity c,shippingarea a where c.city=a.shippingareaid and c.productid=@productid
		select @cityname=stuff(@cityname,1,1,'')
		update product set shortdesc=shortdesc+'(仅限'+@cityname+'购买)' where productid=@productid
	end
end






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtExport_Get]    脚本日期: 04/09/2012 18:28:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas>
-- Create date: <2011-12-22>
-- Description:	<管理后台导出商品>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtExport_Get]
@pids varchar(8000)=null,
@keyword varchar(50)=null,
@catIDs varchar(50)=null,
@brandIDs varchar(50)=null,
@isDel int=-1,--是否是回收站的商品，0不是 1是 -1不限
@isForSale int=null,--是否是上架的商品，0不是 1是 -1不限
@searchType int=null,
@lowprice varchar(50)=null,--价格
@highprice varchar(50)=null,
@lowstorage varchar(50)=null,--库存
@highstorage varchar(50)=null,
@startTime varchar(50)=null,--添加时间
@endTime varchar(50)=null,
@tag varchar(10)=null,--标签
@status int=null,----是否是已审核的商品，0未审核  1已审核 -1审核不过 -2不限
@supplierid int,--是否搜索运营商自已的商品，-2查找所有的商家的商品，-1查找非自营的商品 0查找自营商品 其它值就是查找对应的商家
@errorFlag int=null output,
@errorMsg varchar(200)=null output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
Begin Try
if isnull(@pids,'')=''
begin
declare @sqlstr nvarchar(4000),@where nvarchar(4000),@from nvarchar(4000)
--构造搜索条件
select @where=' 1=1'

if isnull(@isdel,-1)<>-1
select @where=@where+' and isdel='+cast(@isdel as varchar(2))

if isnull(@isforsale,-1)<>-1
select @where=@where+' and isforsale='+cast(@isforsale as varchar(2))

if isnull(@status,-2)<>-2
select @where=@where+' AND p.status='+cast(@status as varchar(2))

--类别catids
--如果搜索中带有分类的话，还要连表查询
if not(@catids='0' or @catids='')
begin
select id,value as CategoryID into #t1 from SplitToTable_Func(@catids,',')
select id,categoryno into #t2 from #t1 ,category c(nolock) where #t1.categoryid=c.categoryid  
select @from='Product p(nolock) left join Supplier s(nolock) on p.SupplierID=s.SupplierID join #t2 on p.categoryno like ''''+cast(#t2.categoryno as varchar(20))+ ''%'''
end
else
begin
select @from='Product p(nolock) left join Supplier s(nolock) on p.SupplierID=s.SupplierID'
end

--@brandids='' 或0时
if  not(@brandids='0' or @brandids='')
select @where=@where+' and brandid in('+@brandids+')'

if isnull(@searchtype,'')<>''
begin
select @where= CASE @searchtype
WHEN 0 THEN @where+'  AND (ProductName Like ''%' + @keyword + '%'' or ProductNo Like ''%' + @keyword + '%'' or p.Keyword Like ''%' + @keyword + '%'''
WHEN 1 THEN @where+' AND ProductNo Like ''%' + @keyword + '%'''
WHEN 2 THEN @where+' AND ProductName Like ''%' + @keyword + '%'''
WHEN 3 THEN @where+' AND p.Keyword Like ''%' + @keyword + '%'''
WHEN 4 THEN @where+' AND p.SupplierID=''' + @keyword + ''''
WHEN 5 THEN @where+' AND SupplierName='''+ @keyword + ''''
END
end

if isnull(@supplierid,-2)<>-2
begin
select @where=CASE @supplierid
WHEN -1 THEN @where+' AND p.SupplierID <>0'
WHEN 0 THEN @where+'  AND p.SupplierID =0'
Else @where+' AND p.SupplierID ='+cast(@supplierid as varchar(2))
END
end

if isnull(@highprice,'')<>''
select @where=@where+' and MemberPrice<=' + @highprice

if isnull(@lowprice,'')<>''
if @lowprice<>''
select @where=@where+' and MemberPrice>=' + @lowprice

if @lowstorage<>''
select @where=@where+' and storage >=' + @lowstorage

if @highstorage<>''
select @where=@where+' and storage <=' + @highstorage

if isnull(@starttime,'')<>''
select @where=@where+' and AddTime>=' + @startTime + ''''

if isnull(@endTime,'')<>''
select @where=@where+' and AddTime<=' + @endTime + ''''

--按商品标签搜索,这里有问题？
--insert log(content)values(@tag)

if  not(@tag='0' or @tag='' or @tag is null)
begin
select id ,value as tagid into #t3 from SplitToTable_Func(@tag,',')
select id,productid into #t4 from #t3,pdttag pt(nolock)where pt.tagid=#t3.tagid
select @from=@from+' join #t4 on p.productid=#t4.productid'
end

--分页的方式得到商品
select @sqlstr='select p.ProductID,p.ProductNo,p.ProductName,p.CategoryID,p.BrandID,p.BrandName,p.unit,p.weight,p.MarketPrice,p.MemberPrice,Storage,score,IsForSale,p.Status
from '+@from+'
where ' + @where + 'order by sort desc'

Execute(@sqlstr)
end
else
begin
select * into #d from SplitToTable_Func(@pids,',')
select p.ProductID,p.ProductNo,p.ProductName,p.CategoryID,p.BrandID,p.BrandName,p.unit,p.weight,p.MarketPrice,p.MemberPrice,Storage,score,IsForSale,p.Status
from product p(nolock),#d d
where p.productid=d.value
end
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtForBaiduOpen_Get]    脚本日期: 04/09/2012 18:28:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2012-02-06>
-- Description:	<商品>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtForBaiduOpen_Get] 
@pageSize int =16,--每页显示
@pageNo int=1,--页码
@totalpage int=null output,--总页数
@totalcount int=null output,--总记录数
@errorflag int=null output,
@errormsg varchar(200)=null output
AS
BEGIN
begin try
declare @sqlstr nvarchar(4000)
declare @where nvarchar(4000)

--取得每个商品中对应的大图sort最小的图片
select * into #pdtimg from pdtimg a
where not exists(select 1 from pdtimg where pid=a.pid and sort<a.sort)

select @where=' isforsale=1 and p.isdel=0 and p.status=1 and supplierid=0 and brandid>0 and brandname<>'''''
select @sqlstr='select * from (
select ProductID,p.CategoryID,c.CategoryNo,ProductName,MemberPrice,BrandName,keyword,p.ImgFolder,ThumbnailImg,Storage,Reviews,Pingfen,img1 as image,cast(name as varchar(150))as tags,Row_number() over(order by productid desc) as rowno
from product p inner join category c on p.categoryid=c.categoryid inner join #pdtimg on p.productid=#pdtimg.pid where '+@where+' )as p where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
--获取分页商品datatable[1]
--insert log(content)values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by productid desc) as rowno from product where '+@where+')as temp)'
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output
select @totalcount=isnull(@totalcount,0)
select @totalpage=ceiling(@totalcount*1.0 / @pagesize)
select @errorflag=0
select @errormsg=''
End Try
Begin Catch
-- 捕捉错误
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch 
END









GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtImg_Get]    脚本日期: 04/09/2012 18:28:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2010-06-23>
-- Description:	<删除商品前先要从服务器上删除的图片>
-- =============================================

CREATE PROC [dbo].[XpProc_PdtImg_Get](
	@pdtids varchar(8000),--要删除的商品ID集合
	@errorFlag int =1 output
)
AS
begin
	select @errorFlag=1
	select *  into #temp from dbo.SplitToTable_Func(@pdtids,',')
	--返回因删除商品同时要删除的图片
	select imgfolder,isnull(img1,'')as img1,isnull(img2,'')as img2,isnull(img3,'') as img3,isnull(img4,'')as img4,isnull(img5,'')as img5,isnull(img6,'')as img6 from pdtimg(nolock) where pid in(select [value]from #temp)
	select @errorFlag=0
end
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtInfo_Select]    脚本日期: 04/09/2012 18:28:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas>
-- Create date: <2011-04-17>
-- Description:	<修改商品时获取商品详细信息>
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20111110                              
content:                                
1.添加输出参数@catpath,用于返回分类路径
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtInfo_Select]
@pid int,
@catpath varchar(100) output
AS
BEGIN
--获取商品基本信息
SELECT 
ProductID,ProductName,CategoryID,ProductNo,BrandID,BrandName,ShortDesc,Unit,Weight,MarketPrice,
MemberPrice,Score,ThumbnailImg,ProductImg,p.Description,PackingList,AfterService,Storage,AarnNum,IsForSale,IsBuyLimited,
IsPackaged,PackageInfo,p.AddTime,p.Status,Sort,IsVirtual,CanReview,IsDiscount,Hits,MiniBuyNum,
Spec,SpecDesc,Properties,SaleNum,p.Title,MetaKeywords,MetaDescription,p.Keyword,p.SupplierID,UseScore,
P1,P2,P3,P4,P5,P6,P7,P8,P9,P10,p.CategoryNo,SubCategoryID,ImgFolder,IsDlvUnit,DlvUnit,IsOfferInvoice,
IsNeedStorage,SkuMap,IsDel,s.SupplierName
into #p
FROM Product p(nolock) 
left join supplier s(nolock) 
on p.supplierID = s.SupplierID
WHERE p.ProductID = @pid

select * from #p

--获取商品图片信息
--select img1,imgfolder from pdtimg where pid=@pid
--select ('http://etp2011.wsdict.com/upload/productimg/'+imgfolder+img1) as img from pdtimg where pid=@pid
select img1 as img,imgfolder,sort from pdtimg where pid=@pid order by sort

--获取关联配件
select p.ProductID,g.GoodsID,g.goodsname,p.ProductName,p.productno,g.MemberPrice,ThumbnailImg,imgfolder,ProductImg,p.img5
from Product p(nolock),Fitting f(nolock),goods g(nolock)
where g.goodsid=f.FitID and f.ProductID=@pid and g.productid=p.productid

--获取相关商品
select p.productid,p.productno,p.productname,p.memberprice,p.imgfolder,p.img5 
from product p(nolock),rltpdts r(nolock) 
where r.productid=@pid and p.productid=r.RltPdtID 
order by r.sort

declare @catno varchar(20)
select @catno=categoryno from #p
select @catpath=''
select @catpath=@catpath+'>>'+cast([name] as varchar) 
from category c(nolock)
where 
left(@catno,len(categoryno))=categoryno and categoryid <>0
order by len(categoryno)
select @catpath=stuff(@catpath,1,2,'')

END










GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtLimitTime_Get]    脚本日期: 04/09/2012 18:28:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-01-29>
-- Description:	<获取限时抢购商品>
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110722                              
content:                                
1.添加是否首页显示功能                                 
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtLimitTime_Get]
@cid int, --分类ID
@top int --读取的条数
AS
BEGIN
select top (@top) p.productid,p.productname,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,p.ProductNo,isnull(balance,0) as balance,unit
from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock)
where g.IsHomeShow=1 and p.productid=g.productid and g.ruleid=r.ruleid and g.basictype='goods' and g.subtype='limittime' and p.CategoryNo Like (Cast(dbo.f_GetCategoryNo(@cid) As nvarchar(30)) + '%') and r.begintime<getdate() and r.endtime>getdate()
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtLimitTime_PageList_Get]    脚本日期: 04/09/2012 18:28:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-05-21>
-- Description:	<分页获取限时抢购商品>
-- Debug:

-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtLimitTime_PageList_Get]
@cid varchar(20)='0',--主分类
@sort varchar(50),--排序
@supplierid int=0,--商家ID
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@totalpage int output,--总页数
@totalcount int output,--总记录数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' p.productid=g.productid and g.ruleid=r.ruleid and g.basictype=''goods'' and g.subtype=''limittime'' and r.begintime<getdate() and r.endtime>getdate()'

if isnull(@cid,'0')<>'0'
select @where=@where+' and p.categoryno like '''+convert(varchar(50),dbo.f_GetCategoryNo(@cid))+'%'''


select @sqlstr='select rowno,productid,productname,shortdesc,marketprice,memberprice,imgfolder,ThumbnailImg,productimg,img5,pmtprice,begintime,endtime,leavingday from (
select p.productid,p.productname,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,Row_number() over('

if isnull(@sort,'')<>''
select @sqlstr=@sqlstr+@sort
else
select @sqlstr=@sqlstr+'order by g.sort,g.addtime desc'

select @sqlstr=@sqlstr+ ') as rowno 
from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) where ' + @where + ') as l where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

--print @sqlstr
--insert into log(content) values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数

select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by g.id desc) as rowno from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) where ' + @where + ') as l)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END








GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtList_Get]    脚本日期: 04/09/2012 18:28:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-12-22>
-- Description:	<管理后台,列出商品>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtList_Get]
@keyword varchar(50)=null,
@catIDs varchar(50)=null,
@brandIDs varchar(50)=null,
@pageno int=1,
@PageSize int=30,
@isDel int=-1,--是否是回收站的商品，0不是 1是 -1不限
@isForSale int=null,--是否是上架的商品，0不是 1是 -1不限
@searchType int=null,
@ispackaged bit=null,
@sortType varchar(50)=null,
@lowprice varchar(50)=null,--价格
@highprice varchar(50)=null,
@lowstorage varchar(50)=null,--库存
@highstorage varchar(50)=null,
@startTime varchar(50)=null,--添加时间
@endTime varchar(50)=null,
@tag varchar(10)=null,--标签
@status int=null,----是否是已审核的商品，0未审核  1已审核 -1审核不过 -2不限
@supplierid int,--是否搜索运营商自已的商品，-2查找所有的商家的商品，-1查找非自营的商品 0查找自营商品 其它值就是查找对应的商家
@totalcount int =null output,
@totalpage int=null output,
@errorFlag int=null output,
@errorMsg varchar(200)=null output
AS
BEGIN
set nocount on
--declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0
Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000),@from nvarchar(4000)
--构造搜索条件
--select @where=' Product.SupplierID=Supplier.SupplierID'
select @where=' 1=1'

if isnull(@isdel,-1)<>-1
select @where=@where+' and isdel='+cast(@isdel as varchar(2))

if isnull(@isforsale,-1)<>-1
select @where=@where+' and isforsale='+cast(@isforsale as varchar(2))

if isnull(@status,-2)<>-2
select @where=@where+' AND p.status='+cast(@status as varchar(2))
--begin
--select @where=CASE @status
--WHEN 0 THEN @where+'  AND Product.status=0'
--WHEN 1 THEN @where+' AND Product.status=1'
--WHEN -1 THEN @where+' AND Product.status=-1'
--END
--end

--类别catids
--如果搜索中带有分类的话，还要连表查询
if not(@catids='0' or @catids='')
begin
select id,value as CategoryID into #t1 from SplitToTable_Func(@catids,',')
select id,categoryno into #t2 from #t1 ,category c(nolock) where #t1.categoryid=c.categoryid  
select @from='Product p(nolock) left join Supplier s(nolock) on p.SupplierID=s.SupplierID join #t2 on p.categoryno like ''''+cast(#t2.categoryno as varchar(20))+ ''%'''
end
else
begin
select @from='Product p(nolock) left join Supplier s(nolock) on p.SupplierID=s.SupplierID'
end

--@brandids='' 或0时
if  not(@brandids='0' or @brandids='')
select @where=@where+' and brandid in('+@brandids+')'

if isnull(@searchtype,-1)<>-1
--if @searchtype is not null
begin
select @where= CASE @searchtype
WHEN 0 THEN @where+'  AND (ProductName Like ''%' + @keyword + '%'' or ProductNo Like ''%' + @keyword + '%'' or p.Keyword Like ''%' + @keyword + '%'')'
WHEN 1 THEN @where+' AND ProductNo Like ''%' + @keyword + '%'''
WHEN 2 THEN @where+' AND ProductName Like ''%' + @keyword + '%'''
WHEN 3 THEN @where+' AND p.Keyword Like ''%' + @keyword + '%'''
WHEN 4 THEN @where+' AND p.SupplierID=''' + @keyword + ''''
WHEN 5 THEN @where+' AND SupplierName='''+ @keyword + ''''
END
end

if isnull(@ispackaged,'')<>''
select @where=@where+' and ispackaged'+ cast(@ispackaged as varchar(2))

if isnull(@supplierid,-2)<>-2
begin
select @where=CASE @supplierid
WHEN -1 THEN @where+' AND p.SupplierID <>0'
WHEN 0 THEN @where+'  AND p.SupplierID =0'
Else @where+' AND p.SupplierID ='+cast(@supplierid as varchar(2))
END
end

if isnull(@highprice,'')<>''
select @where=@where+' and MemberPrice<=' + @highprice

if isnull(@lowprice,'')<>''
if @lowprice<>''
select @where=@where+' and MemberPrice>=' + @lowprice

if @lowstorage<>''
select @where=@where+' and storage >=' + @lowstorage

if @highstorage<>''
select @where=@where+' and storage<=' + @highstorage

if isnull(@starttime,'')<>''
select @where=@where+' and AddTime>=' + @startTime + ''''

if isnull(@endTime,'')<>''
select @where=@where+' and AddTime<=' + @endTime + ''''

--按商品标签搜索,这里有问题？
--insert log(content)values(@tag)

if  not(@tag='0' or @tag='' or @tag is null)
begin
select id ,value as tagid into #t3 from SplitToTable_Func(@tag,',')
select id,productid into #t4 from #t3,pdttag pt(nolock)where pt.tagid=#t3.tagid
--select @where=@where+' and ProductID in (select ProductID from PdtTag where TagID IN (' + @tag + '))'
select @from=@from+' join #t4 on p.productid=#t4.productid'
end

--if isnull(@sortType,'')<>''
--begin
--select @where=CASE @sortType
--WHEN 'SaleNum' THEN @where+'  ORDER BY SaleNum DESC'
--WHEN 'Sort' THEN @where+' ORDER BY Sort DESC'
--else @where+' ORDER BY Sort DESC'
--END
--end

declare @sort varchar(50)
select @sort= CASE @sortType WHEN 'SaleNum' THEN 'ORDER BY SaleNum DESC' WHEN 'Sort' THEN 'ORDER BY Sort DESC' else 'ORDER BY Sort DESC' end
--分页的方式得到商品

select @sqlstr='select *from(select p.ProductID,p.ProductName,p.CategoryID,p.CategoryNo,MarketPrice,MemberPrice,ProductNo,
Storage,
ThumbnailImg,Sort,IsForSale,BrandID,SaleNum,ProductGroup,Spec,SpecDesc,p.Status,ImgFolder,SupplierName,
Row_number() over('+@sort+') as rowno
from '+@from+'
where ' + @where + ') as pa where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over('+@sort+') as rowno 
--from Product p(nolock) left join Supplier s(nolock) on p.supplierid=s.supplierid left join #t1 on p.categoryid=#t1.categoryid
from '+@from+'
where ' + @where + ') as p)'
--print @sqlstr

Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=Ceiling(cast(@totalcount as float)/@pageSize)
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
END








GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtList_Search]    脚本日期: 04/09/2012 18:28:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-11-20>
-- Description:	<搜索商品>
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20111118                              
content:                                
1.修改了获取该分类下品牌datatable[2]的方法
*/

/*
declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
exec XpProc_PdtList_Search '格兰仕','charindex(''格'',productname)>0',12,-1,-1,0,0,'','order by memberprice asc',-1,10,1,@totalpage output,@totalcount output,@errorflag output,@errormsg output
select @totalpage,@totalcount,@errorflag,@errormsg

declare @position varchar(300),@totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
exec XpProc_PdtList_Search '','',12,-1,0,0,0,'',0,'order by memberprice asc',-1,'',10,1,@position output,@totalpage output,@totalcount output,@errorflag output,@errormsg output
select @position,@totalpage,@totalcount,@errorflag,@errormsg
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtList_Search]
(
	@keyword varchar(100)='',  --关键字
	@keysql varchar(1000)=null,
	@cid varchar(20)=null,--主分类
	@subcat varchar(20)=null,--店内分类
	@bid varchar(20)=null,--品牌ID
	@lowprice decimal(18,2)=null,--价格区间下限
	@highprice decimal(18,2)=null,--价格区间上限
	@p varchar(1000)=null,--属性
	@tagid int,--商品状态标志（pdttag）
	@sort varchar(50)=null,
	@supplierid int=0,--商家ID
	@recent varchar(200), --最近浏览商品的ID字符串
	@pagesize int=10,--每页显示商品数
	@pageno int=1,--页码	
	@position varchar(300) output, --当前位置
	@totalpage int output,--总页数
	@totalcount int output,--总记录数
	@errorflag int output,
	@errormsg varchar(200) output
)
as
begin
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

declare @cno varchar(20)
select @cno=categoryno from Category where categoryid=@cid

Begin Try
--获取分类详细信息datatable[0]
SELECT CategoryNo,[Name],ParentNo,ProductAd FROM Category WHERE CategoryID=@cid

declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' Isforsale=1 and isdel=0 and status=1 '

if isnull(@supplierid,-1)<>-1
select @where=@where+' and supplierid='+convert(varchar(20),@supplierid)

if isnull(@cid,0)<>0
select @where=@where+' and p.categoryno like '''+isnull(@cno,'1')+'%'''

if isnull(@subcat,0)<>0
select @where=@where+' and SubCategoryID like '''+@subcat+'%'''

if isnull(@bid,0)<>0
select @where=@where+' and brandid = '+@bid

if isnull(@lowprice,0)<>0
select @where=@where+' and memberprice >= '+convert(varchar(20),@lowprice)

if isnull(@highprice,0)<>0
select @where=@where+' and memberprice <= '+convert(varchar(20),@highprice)

if isnull(@p,'')<>''
select @where=@where+@p

if isnull(@tagid,0)<>0
select @where=@where+' and p.productid in(Select Distinct(ProductID) From PdtTag Where TagID='+convert(varchar(20),@tagid)+')'

if isnull(@keysql,'')<>''
select @where=@where+' and '+@keysql

select @sort=isnull(@sort,'order by p.sort')

select @sqlstr='select rowno,productid,productname,productno,shortdesc,marketprice,memberprice,imgfolder,ThumbnailImg,reviews,PiNo from (
select p.productid,p.productname,p.productno,p.shortdesc,p.marketprice,isnull(g.pmtprice,p.memberprice) as memberprice,p.imgfolder,p.ThumbnailImg,reviews,case when g.subtype=''limittime'' then 16 when g.subtype=''specialprice'' then 2 when g.subtype=''coupon'' then 10 when PiEndTime>getdate() then PiNo else 0 end as PiNo,Row_number() over('+@sort+') as rowno 
from product p(nolock)
left join PmtGoodsList g      
on( p.productid=g.productid and g.BasicType=''goods'' and g.SubType in(''discount'',''specialprice'',''limittime'',''coupon''))  
where ' + @where + ') as p where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

print @sqlstr
--insert into log(content) values(@sqlstr)
--获取分页商品datatable[1]
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over('+@sort+') as rowno from product p(nolock) where ' + @where + ') as p)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

select @totalcount=isnull(@totalcount,0)
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage

--获取该分类下品牌datatable[2]
SELECT DISTINCT(c.BrandID),brandname FROM Brand b(nolock),CatBrand c(nolock),Category t(nolock)
WHERE b.brandid=c.brandid and t.categoryid=c.categoryid and t.categoryno Like (@cno + '%') 

--获取筛选属性datatable[3]
Select Props from Category c(nolock),PdtType p(nolock) where c.CategoryID = @cid and c.TypeID = p.TypeID

--获取该类销售排行榜datatable[4]
select top 10 p.ProductID,ProductName,productno,MarketPrice,MemberPrice,imgfolder,productimg,isnull(t.Sort,99999999) as sort 
from product p(nolock) 
left join topsale t(nolock) on (t.productid=p.productid and t.CategoryID=@cid)
where  categoryno Like (@cno + '%') and isforsale=1 and status=1
order by sort,p.SaleNum desc

--最近浏览过的商品datatable[5]
exec XpProc_PdtRecentView_Get @recent

--获取该分类热卖推荐商品datatable[6]
SELECT TOP 4 p.ProductID,ProductName,p.CategoryNo,ProductNo,BrandName,ShortDesc,MarketPrice,Score,MemberPrice,ThumbnailImg,ProductImg,ImgFolder,Img5 
FROM Product p(nolock)
left join PdtTag t(nolock) 
on t.ProductID = p.ProductID and tagid=3 and t.CategoryNo Like (@cno + '%')
Where p.Isforsale=1 and p.isdel=0 and p.categoryno like (@cno + '%')
Order By t.Sort desc,p.sort

--获取该分类顶级分类关联的文章datatable[7]
select top 5 ArticleID,Title 
from category c(nolock),News_Article a(nolock) 
where c.categoryno=left(@cno,4) and c.NewsCatID=a.CategoryID
order by IsTop DESC,AddTime DESC

--获取当前位置
exec p_get_category_path @cid,@bid,@position output

/*
--当关键字不为空，说明是搜索页面调用，要返回分类及品牌的分组结果
if isnull(@keyword,'') <> ''
	begin
		--在所有exec前创建一个空的临时表，以便在所有exec中共用
		select top 0 convert(int,productid) as productid,productname,productno,categoryid,categoryno,brandid,ImgFolder,ThumbnailImg,isforsale,isdel,supplierid into #p 
		from product p(nolock) 

		--往临时表#p插入记录
		select @sqlstr = 'insert into #p select productid,productname,productno,categoryid,categoryno,brandid,ImgFolder,ThumbnailImg,isforsale,isdel,supplierid from product p(nolock) where ' +  @where
		EXEC (@sqlstr)
		--insert into a(a,remark) values(@sql,'list_#p')

		--把#p中的数据根据分类分组
		set @sqlstr = 'select c.categoryid,c.[name],count(p.productid) as pnum from #p p(nolock) ,category c(nolock) where p.categoryid = c.categoryid and ' +  @where + 'group by c.categoryid,c.[name] order by pnum desc'
		EXEC (@sqlstr)
		print @sqlstr
		--insert into a(a,remark) values(@sql,'list_cat')
		
		--把#p中的数据根据品牌分组
		set @sqlstr = 'select b.brandid,b.brandname,count(p.productid) as pnum from #p p(nolock) ,brand b(nolock) where p.brandid = b.brandid  and ' +  @where + 'group by b.brandid,b.brandname order by pnum desc'
		EXEC (@sqlstr)
		print @sqlstr
		--insert into a(a,remark) values(@sql,'list_brand')
		
		if(len(@keyword) > 1 and @totalcount>0)--关键字不为单字符且记录数大于0才记录或更新关键字热度和搜索结果数
			begin
				declare @keycount int
				select @keycount=count(id) from keyword where KeyWord = @keyword
				if(@keycount>0)--存在该关键字记录，更新热度及搜索结果
					begin
						update KeyWord set KeyHot = KeyHot+1,Records = @totalcount where KeyWord = @keyword
					end
				else
				begin
					insert KeyWord (KeyWord,Records) values (@keyword,@totalcount)
				end
			end
	end
*/
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch

end



















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtPromotion_PageList_Get]    脚本日期: 04/09/2012 18:28:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-05-21>
-- Description:	<分页促销专题活动商品>
-- Debug:

-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtPromotion_PageList_Get]
@ruleid int,--活动规则ID
@sort varchar(50),--排序
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@totalpage int output,--总页数
@totalcount int output,--总记录数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
--获取规则信息
select rulename,ruleno,basictype,subtype,pmttype,remark,rulead,begintime,endtime from pmtrule(nolock) where ruleid=@ruleid
--分页获取促销商品
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' p.productid=g.productid and g.ruleid=r.ruleid and r.ruleid='+convert(varchar(20),@ruleid)

select @sqlstr='select rowno,productid,productname,shortdesc,marketprice,memberprice,imgfolder,ThumbnailImg,productimg,img5,pmtprice,begintime,endtime from (
select p.productid,p.productname,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,isnull(g.pmtprice,p.memberprice) as pmtprice,r.begintime,r.endtime,Row_number() over('

if isnull(@sort,'')<>''
select @sqlstr=@sqlstr+@sort
else
select @sqlstr=@sqlstr+'order by g.sort,g.addtime desc'

select @sqlstr=@sqlstr+ ') as rowno 
from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) where ' + @where + ') as l where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

--print @sqlstr
--insert into log(content) values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数

select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by g.id desc) as rowno from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) where ' + @where + ') as l)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END











GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtRecentView_Get]    脚本日期: 04/09/2012 18:28:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakks@qq.com>
-- Create date: <2010-05-10>
-- Description:	<获取最近浏览商品>
-- Debug: exec XpProc_PdtRecentView_Get '47,570'
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtRecentView_Get] 
@recent varchar(200)--通过分隔符隔开的商品ID
AS
begin
select * into #r from SplitToTable_Func(@recent,',') 
select ProductID,ProductName,ProductNo,MarketPrice,MemberPrice,ThumbnailImg,ProductImg,ImgFolder ,Unit From product p,#r r Where p.productid = r.value and Status=1 and IsForSale = 1 and IsPackaged = 0 order by r.id
end

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtRelateInfo_Get]    脚本日期: 04/09/2012 18:28:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<hakkas>
-- Create date: <2011-04-17>
-- Description:	<获取商品详细页面的相关的信息>
-- Debug: exec XpProc_PdtRelateInfo_Get 437,-1
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtRelateInfo_Get]
@pid int, --商品ID
@mid int, --会员ID
@recent varchar(200) --最近浏览商品的ID字符串
AS
BEGIN
--查询商品参与的活动信息放到临时表
select * 
into #p
from PmtGoodsList p(nolock)
where 
p.productid=@pid

--select * from #p

--从商品中得到商家ID,分类ID
declare @sid int,@categoryid int
select @sid=supplierid,@categoryid=categoryid from product where productid=@pid

--商品详情  datatable[0]
SELECT top 1
p.ProductID,p.ProductName,p.CategoryID,p.CategoryNo,p.ProductNo,p.BrandID,p.BrandName,p.ShortDesc,p.Unit,p.Weight,IsForSale,p.Status,
p.MarketPrice,p.MemberPrice,Score,ThumbnailImg,ProductImg,p.Description,AfterService,Storage,PackageInfo,PackingList,p.AddTime,
Hits,MiniBuyNum,Spec,SpecDesc,Properties,SaleNum,p.Title,MetaKeywords,MetaDescription,UseScore,
ImgFolder,IsDlvUnit,DlvUnit,IsOfferInvoice,p.Reviews,p.PJ1,p.PJ2,p.PJ3,p.PJ4 ,p.PJ5,
p.SupplierID,s.SupplierName,s.address,p.PingFen,IsNeedStorage,SkuMap, 
--ProductGroup,PackingList,AarnNum,IsBuyLimited,IsPackaged,StartTime,EndTime,
--RelatedImgs,Sort,IsVirtual,CanReview,IsDiscount,p.Keyword,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,SubCategoryID,
case when p0.productid is not null then 1  else 0 end ispromotion,--是否参与促销
p1.pmtprice,--抢购价
p2.endtime as pmtendtime,--抢购结束时间
p2.Balance,--剩余抢购数量
case when p.reviews>0 then rtrim(cast((p.pj1+p.pj2)*1.0/p.reviews*100 as decimal(5,0)))+'%' else '0%' end as hpd, --好评度
case when p.reviews>0 then rtrim(cast(p.pj3*1.0/p.reviews*100 as decimal(5,0)))+'%' else '0%' end as zpd, --中评度
case when p.reviews>0 then rtrim(cast((p.pj4+p.pj5)*1.0/p.reviews*100 as decimal(5,0)))+'%' else '0%' end as cpd--差评度
FROM Product p(nolock)
left join Supplier s(nolock)
on(p.SupplierID=s.SupplierID)
left join #p p0(nolock)
on (
  p0.productid=p.productid
)
left join #p p1(nolock)
on (
  p1.productid=p.productid
  --and p.productid=@pid
  and p1.isspecprice=1--特价
)
left join #p p2(nolock)
on(
  p2.productid=p.productid
  and p2.islimittimes=1--抢购活动结束时间 
) 
WHERE p.ProductID=@pid

--商品的相关图片 datatable[1] img1为原图，img2为300*300 img6为50*50
select img1,img2,img6,imgfolder from pdtimg(nolock) where pid=@pid order by sort

--显示促销列表信息datatable[2]
select * 
from  #p

--同类销售排行榜 datatable[3]
select top 10 p.ProductID,ProductName,ProductNo,CategoryNo,MemberPrice,ThumbnailImg,ProductImg,img5,ImgFolder,salenum,img5
from product p(nolock) 
left join topsale t 
on t.ProductID = p.ProductID and t.CategoryID=@categoryid
where isforsale=1 and status=1 and p.CategoryID=@categoryid
order by t.sort,p.SaleNum desc

--商家热卖商品 datatable[4]
select top 10 productid,productname,thumbnailimg ,salenum,marketprice,memberprice,CategoryNo,imgfolder,ProductImg,img5 
from product(nolock) 
where Status = 1 and IsForSale =1 and IsPackaged = 0  and supplierid= (@sid) 
order by salenum desc

--最近浏览过的商品datatable[5]
exec XpProc_PdtRecentView_Get @recent

--推荐配件datatable[6]
select p.ProductID,p.ProductName,g.MemberPrice,ThumbnailImg,imgfolder,ProductImg,p.img5,g.GoodsID
from Product p(nolock),Fitting f(nolock),goods g(nolock)
where g.goodsid=f.FitID and f.ProductID=@pid and g.productid=p.productid

--相关商品 datatable[7]
select p.ProductID,p.ProductName,CategoryID,CategoryNo,ProductNo,ShortDesc,MarketPrice,MemberPrice,ThumbnailImg,imgfolder,ProductImg,p.img5 
from Product p(nolock),RltPdts r(nolock) 
where p.ProductID = r.RltPdtID and r.ProductID = @pid and p.Status = 1 and p.IsForSale =1 and p.IsPackaged = 0

--相关套装datatable[8]
select suitid,suitname,oldprice,price,(oldprice-price) as lessmoney from suit where MainPdtID=@pid and getdate() between begintime and endtime and balance>0

--套装明细datatable[9]
select d.suitid,d.productid,p.productname,goodsid,imgfolder,img5,quantity,d.sort
from suit s(nolock),suitdetail d(nolock),product p(nolock)
where s.MainPdtID=@pid and d.suitid=s.suitid and d.productid=p.productid and getdate() between s.begintime and s.endtime and s.balance>0
order by ismaster desc,sort 

--更新商品的浏览量
update product set hits=hits+1 where productid=@pid
/*
--购买此商品的会员还购买过 datatable[1]
--在OrderProduct中，根据@pid 得到OrderID,再查找此OrderID对应的商品的Productid,最后连接Product表
declare @tempTable table(productid int ,productname nvarchar(510),subcategoryid varchar(20), prouductno nvarchar(100),storage int,Thumbnailimg nvarchar(100),memberprice decimal(18,2),marketprice decimal(18,2),CategoryID int,categoryno varchar(20))
insert  @temptable 
Select top 10 ProductID,ProductName,SubCategoryid,ProductNo,Storage,ThumbnailImg,MemberPrice,MarketPrice,CategoryID,CategoryNo
From Product
Where ProductID In (Select Distinct(ProductID) From OrderProduct Where OrderID In (Select OrderID From OrderProduct Where ProductID=@pid) And ProductID<>@pid) 
And Status=1 and IsPackaged=0 
Order By NewID()

--如果在订单表中存在纪录
if exists(select *from @temptable)
begin
	select * from @temptable
end
else
begin
	insert  @temptable Select top 10 ProductID,ProductName,subcategoryid,ProductNo,Storage,ThumbnailImg,MemberPrice,MarketPrice,CategoryID,CategoryNo 
	From Product 
	Where subcategoryid Not In (Select Distinct(subcategoryid) From Product Where ProductID =@pid) And ProductID <>@pid And Status=1 and  IsPackaged = 0  and subcategoryid is not null Order By NewID()
	select * from @temptable
end
*/

--商家详情 datatable[3]
--select supplierid,suppliername,address from supplier(nolock) where supplierid=@sid

end












GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtReview_BatchAdd]    脚本日期: 04/09/2012 18:28:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-08-26>
-- Description:	<后台对商品的批量评价>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtReview_BatchAdd] (
@productID int , --产品ID
@title Nvarchar(255), --评价标题
@body ntext,--评价内容
@score int,--评分
@addtime DateTime,--评论时间
@memberName NVarchar(50), --评论人账号
@ip varchar(40),--评价人IP
@OperatorID int,--执行批量插入管理员ID，将会插入到auditor字段
@operatorName varchar(20),--执行批量插入管理员字，将会插入到auditorname字段
@errorFlag int out,     --是否错误标识，<>0 时，显示错误信息@errorMessage nvarchar(100)='' out   --错误信息提示 
@errorMsg varchar(200)='' out
)
AS
begin
	begin try
	declare @supplierID int--商家ID
	select @supplierID=supplierid from product(nolock) where productid=@productid

	--不能给系统中已注册的会员添加商品评论
	if exists (select *from member where name =@memberName)
	begin
	select @errorFlag=1
	select @errorMsg='不能给系统中已注册的会员添加评论'
	return
	end
--	--同一条记录不能二次插入
--    if exists(select *from productreview where membername=@membername and addtime=@addtime)
--	begin
--	select @errorFlag=1
--	select @errorMsg='这个会员的这条评论已存在'
--	return
--	end
	begin tran
	--生成商品购买时间,购买时间+3<评价时间为<购买时间+20
	declare @orderTime datetime
	select @orderTime=dateadd(minute,-floor((28800-4320)*rand()+4320),@addtime)
	--插入商品评价，并把状态置为已审核
	insert ProductReview(ProductID,MemberID,Title,Body,Score,AddTime,IP,YesNum,NotNum,Status,MemberName,MemberScore,ReviewType,IsToMessage,OrderTime,SupplierID,IsReply,Auditor,Auditorname,AuditorIP,AuditTime)
	values(@productID,-1,@title,@body,@score,@addtime,@ip,0,0,2,@membername,0,1,0,@ordertime,isnull(@supplierID,''),0,@operatorID,@operatorName,@ip,getDate())
	begin 
		print('加评论数')
		if(@score=1)
		begin
			update product set reviews=isnull(reviews,0)+1,pj5=isnull(pj5,0)+1 where productid=@productid
		end
		else if(@score=2)
		begin
			update product set reviews=isnull(reviews,0)+1,pj4=isnull(pj4,0)+1 where productid=@productid
		end
		else if(@score=3)
		begin
			update product set reviews=isnull(reviews,0)+1,pj3=isnull(pj3,0)+1 where productid=@productid  
		end 
		else if(@score=4)
		begin
			update product set reviews=isnull(reviews,0)+1,pj2=isnull(pj2,0)+1 where productid=@productid  
		end 
		else 
		begin 
			update product set reviews=isnull(reviews,0)+1,pj1=isnull(pj1,0)+1 where productid=@productid  
		end 
		print('更新商品平均评分') 
		update product set pingfen=(select cast(round(avg(score*1.0),0) as int) from productreview where status=2 and productid =@productid group by productid)  where productid = @productid
	end
	select @errorFlag=0
	select @errorMsg='操作成功'
	commit tran
	end try
	begin catch
	rollback
	select @errorFlag=1
	select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
	end catch
end








GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtReviewList_Get]    脚本日期: 04/09/2012 18:28:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-08-25>
-- Description:	<分页得到商品评论的数据>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtReviewList_Get](
@curPage int=1,--页码
@pageSize int=30,--每页显示的评论数
@productID int=null,--商品ID
@score int=null, --商品评论的分数,0表示所有的分数
@status int,--为0获取未审批的记录 1获取所有已审批的记录 2:获取所有已审批的记录及会员自己的审核不过的记录 -1:获取所有审批未过的记录
@memberID int=null,--当前操作的会员ID,
@reviewType int=1,--回复的类型
@isGetMemberGroupInfo bit=1,--是否显示会员组的信息
@isShowPName bit=1,--前台还是后台调用的标志位。0前台，1管理后台
@searchType int=null,--后台查找评论的类型 1按会员号 2商品名称 3商品编码
@keyword varchar(100)=null,--后台查找的关键字
@startTime varchar(10)=null,--后台查找的开始时间
@endTime varchar(10)=null,--后台查找的结束时间
@totalCount int output,--查找结果的总数
@errorFlag int output,
@errorMsg varchar(200) output
)
as
begin
Begin Try
select @errorFlag=0
select @errorMsg=''
select @totalCount=0
declare @sqlstr nvarchar(4000),
@where nvarchar(4000),--查询的条件
@table nvarchar(4000), --要查找的表，因为有可能要左连接Product,member,memberGroup等表
@colname nvarchar(4000) --select出来的各个字段，因为连表不同，字段也不同
select @table='ProductReview' 
select @colname='select ProductReviewID,MemberName,ProductReview.Title,Body,productreview.Score,YesNum,NotNum,ProductReview.AddTime' 
select @where=' 1=1 '
--构造查询条件
if isnull(@productID,0)<>0
select @where =@where+ ' and ProductReview.ProductID='+cast(@productID as varchar(10))

if(@status=-1)
	select @where=@where+' and ProductReview.Status=1'
else if(@status=0)
	select @where=@where+ ' and ProductReview.Status = 0'
else if(@status=1)
	select @where=@where+ ' and (ProductReview.Status=1 or ProductReview.Status=2)'
else if(@status=2)
begin
	if isnull(@memberid,0)<>0
	select @where=@where+ ' and (ProductReview.Status=2 or (ProductReview.Status=1 AND ProductReview.MemberID='+cast(@memberid as varchar(10))+'))'
	else
	select @where=@where+ ' and ProductReview.Status=2'
end

--回复类型
select @where=@where+' and ReviewType= '+cast (@reviewType as varchar(1))

if isnull(@score,0)<>0--因为前台传过来的值，1表示很好，5表示很差，跟数据库里的Score表示相反
begin
select @score=6-@score
select @where=@where+' and ProductReview.Score='+ cast(@score as varchar(1))
end

if isnull(@isGetMemberGroupInfo,0)=1--前台要显示会员组信息，要左连接member,membergroup,跟orders三个表
begin
	select @colname=@colname+',Member.MemberID,Member.GroupID,isnull(groupName,''普通会员'')as GroupName,isnull(Logo,''none.gif'') as Logo,substring(receiveraddress,1,case when charindex('','',receiveraddress)-1 <0 then 0 else charindex('','',receiveraddress)-1 end) as Address'
	select @table=@table+' left join member on ProductReview.MemberID = Member.MemberID left join membergroup on member.groupid=membergroup.membergroupid  left join orders on productreview.orderid=orders.orderid'
end

--后台调用，构造出后台搜索条件
if isnull(@isShowPName,0)=1
begin
select @colname =@colname+' ,ProductName,Product.ProductID'
select @table=@table+' left join Product on ProductReview.Productid=Product.Productid'
if(@searchtype=1)
select @where=@where+' AND ProductReview.MemberName = ''' + @keyword+''''
else if(@searchtype=2)
select @where=@where+' AND Product.ProductName like ''%' + @keyword + '%'''
else if(@searchtype=3)
select @where=@where+' AND Product.no like ''%' + @keyword + '%'''
end
if isnull(@starttime,'')<>''
select @where=@where+' and DateDiff(day, ProductReview.AddTime, ' + 'cast('''+@starttime +''' as Datetime)) <1'
if isnull(@endtime,'')<>''
select @where=@where+' and DateDiff(day, ProductReview.AddTime, ' + 'cast('''+@endtime +''' as Datetime)) >-1'
--后台搜索条件结束

--获得分页数据
select @sqlstr='select * from('+@colname +',Row_number() over(order by ProductReview.Addtime desc) as rowno  from '+ @table+' where'+@where
+')as p where rowno>'+ convert(varchar(50),(@curPage-1)*@pagesize) + ' and rowno<=' + convert(varchar(50),@pagesize*@curPage)
insert log (content)values(@sqlstr)
exec (@sqlstr)

--获取总记录数
select @sqlstr=N'select @rows=(select max(rowno)from (select Row_number() over(order by ProductReview.Addtime desc) as rowno from '+@table+' where '+@where +')as p)'
--insert log(content)values(@sqlstr)
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output
select  @totalcount=isnull(@totalcount,0)

End Try
Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
end

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtSearch_Get]    脚本日期: 04/09/2012 18:28:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-05-21>
-- Description:	<管理后台搜索商品>
-- Debug:
/*
declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
declare @key varchar(100),@cid varchar(20),@subcat varchar(20),@bid varchar(20),@pids varchar(2000),@productno varchar(20),@status int,@lowprice decimal(18,2),@highprice decimal(18,2),@lowstock int,@highstock int,@starttime varchar(50),@endtime varchar(50),@tag varchar(100),@supplierid int,@pagesize int,@pageno int
select @key='',@cid='-1',@subcat='-1',@bid='-1',@pids='',@productno='',@status=1,@lowPrice=0,@highprice=0,@lowstock=0,@highstock=0,@starttime='',@endtime='',@tag='',@supplierid=0,@pagesize=15,@pageno=1
exec XpProc_PdtSearch_Get @key,@cid,@subcat,@bid,@pids,@productno,@status,@lowPrice,@highprice,@lowstock,@highstock,@starttime,@endtime,@tag,@supplierid,@pagesize,@pageno,@totalpage output,@totalcount output,@errorflag output,@errormsg output
select @totalpage,@totalcount,@errorflag,@errormsg
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtSearch_Get]
@key varchar(100)=null,--关键字
@cid varchar(20)=null,--主分类
@subcat varchar(20)=null,--店内分类
@bid varchar(20)=null,--品牌ID
@pids varchar(2000)=null,--逗号分隔的商品ID字符串
@productno varchar(20)=null,--商品编号
@status int=null,--商品状态
@lowprice decimal(18,2)=null,--价格区间下限
@highprice decimal(18,2)=null,--价格区间上限
@lowstock int=null,--库存区间下限
@highstock int=null,--库存区间上限
@starttime varchar(50)=null,--添加时间下限
@endtime varchar(50)=null,--添加时间上线
@tag varchar(100)=null,--标签
@supplierid int=0,--商家ID
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@totalpage int output,--总页数
@totalcount int output,--总记录数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
--declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' Isforsale=1 and isdel=0 and status=1 and supplierid = '+convert(varchar(20),@supplierid)

if isnull(@cid,-1)<>-1
select @where=@where+' and categoryno like '''+convert(varchar(50),dbo.f_GetCategoryNo(@cid))+'%'''

if isnull(@bid,-1)<>-1
select @where=@where+' and brandid = '+@bid

if isnull(@productno,'')<>''
select @where=@where+' and productno = '+@productno

if isnull(@status,9999)<>9999
select @where=@where+' and status = '+convert(varchar(10),@status)

if isnull(@lowprice,0)<>0
select @where=@where+' and memberprice >= '+convert(varchar(20),@lowprice)

if isnull(@highprice,0)<>0
select @where=@where+' and memberprice <= '+convert(varchar(20),@highprice)

if isnull(@lowstock,0)<>0
select @where=@where+' and storage >= '+convert(varchar(20),@lowstock)

if isnull(@highstock,0)<>0
select @where=@where+' and storage <= '+convert(varchar(20),@highstock)

if isnull(@starttime,'')<>''
select @where=@where+' and addtime >='+@starttime

if isnull(@endtime,'')<>''
select @where=@where+' and addtime <= '+@endtime

if isnull(@pids,'')<>''
select @where=@where+' and productid in (' + @pids + ')'

if isnull(@key,'')<>''
select @where=@where+' and productname like ''%' + @key + '%'''

if isnull(@subCat,'0')<>'0'
select @where=@where+' and subcategoryid like'''+@subcat+'%'''


select @sqlstr='select * from (
select productid,productname,productno,categoryid,brandid,memberprice,productimg,imgfolder,Row_number() over(order by productid desc) as rowno 
from product(nolock)
where ' + @where + ') as p where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

--print @sqlstr
--insert into log(content) values(@sqlstr)
--select *from log order by addtime desc 
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by productid desc) as rowno from product(nolock) where ' + @where + ') as p)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END












GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtSearch_Init]    脚本日期: 04/09/2012 18:28:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-11-20>
-- Description:	<前台搜索商品>
/*
declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
exec XpProc_PdtList_Search '格兰仕','charindex(''格'',productname)>0',12,-1,-1,0,0,'','order by memberprice asc',-1,10,1,@totalpage output,@totalcount output,@errorflag output,@errormsg output
select @totalpage,@totalcount,@errorflag,@errormsg
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtSearch_Init]
(
	@keyword varchar(100)='',  --关键字
	@keysql varchar(1000)=null,
	@cid varchar(20)=null,--主分类
	@subcat varchar(20)=null,--店内分类
	@bid varchar(20)=null,--品牌ID
	@lowprice decimal(18,2)=null,--价格区间下限
	@highprice decimal(18,2)=null,--价格区间上限
	@p varchar(1000)=null,--属性
	@sort varchar(50)=null,
	@supplierid int=0,--商家ID
	@pagesize int=10,--每页显示商品数
	@pageno int=1,--页码	
	@position varchar(300) output, --当前位置
	@totalpage int output,--总页数
	@totalcount int output,--总记录数
	@errorflag int output,
	@errormsg varchar(200) output
)
as
begin
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

declare @cno varchar(20)
select @cno=categoryno from Category where categoryid=@cid

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' Isforsale=1 and isdel=0 and p.Status=1 '

if isnull(@supplierid,-1)<>-1
select @where=@where+' and supplierid='+convert(varchar(20),@supplierid)

if isnull(@cid,0)<>0
select @where=@where+' and p.categoryno like '''+@cno+'%'''

if isnull(@subcat,0)<>0
select @where=@where+' and SubCategoryID like '''+@subcat+'%'''

if isnull(@bid,0)<>0
select @where=@where+' and p.brandid = '+@bid

if isnull(@lowprice,0)<>0
select @where=@where+' and memberprice >= '+convert(varchar(20),@lowprice)

if isnull(@highprice,0)<>0
select @where=@where+' and memberprice <= '+convert(varchar(20),@highprice)

if isnull(@p,'')<>''
select @where=@where+@p

if isnull(@keysql,'')<>''
select @where=@where+' and '+@keysql

select @sort=isnull(@sort,'order by p.sort')

select @sqlstr='select rowno,productid,productname,productno,shortdesc,marketprice,memberprice,imgfolder,ThumbnailImg,reviews,PiNo from (
select p.productid,p.productname,p.productno,p.shortdesc,p.marketprice,isnull(g.pmtprice,p.memberprice) as memberprice,p.imgfolder,p.ThumbnailImg,p.reviews,case when g.subtype=''limittime'' then 16 when g.subtype=''specialprice'' then 2 when g.subtype=''coupon'' then 10 when PiEndTime>getdate() then PiNo else 0 end as PiNo,Row_number() over('+@sort+') as rowno 
from product p(nolock)
left join PmtGoodsList g      
on( p.productid=g.productid and g.BasicType=''goods'' and g.SubType in(''discount'',''specialprice'',''limittime'',''coupon''))  
where ' + @where + ') as p where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

print @sqlstr
--insert into log(content) values(@sqlstr)
--获取分页商品datatable[0]
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over('+@sort+') as rowno from product p(nolock) where ' + @where + ') as p)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

select @totalcount=isnull(@totalcount,0)
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage

--获取当前位置
exec p_get_category_path @cid,@bid,@position output

--在所有exec前创建一个空的临时表，以便在所有exec中共用
select top 0 convert(int,productid) as productid,productname,productno,categoryid,categoryno,brandid,memberprice,ImgFolder,ThumbnailImg,isforsale,isdel,status,supplierid into #p 
from product p(nolock) 

--往临时表#p插入记录
select @sqlstr = 'insert into #p select productid,productname,productno,categoryid,categoryno,brandid,memberprice,ImgFolder,ThumbnailImg,isforsale,isdel,status,supplierid from product p(nolock) where ' +  @where
EXEC (@sqlstr)
--insert into a(a,remark) values(@sql,'list_#p')

--把#p中的数据根据分类分组
set @sqlstr = 'select c.categoryid,c.[name],count(p.productid) as pnum from #p p(nolock) ,category c(nolock) where p.categoryid = c.categoryid and ' +  @where + 'group by c.categoryid,c.[name] order by pnum desc'
--获取分类分组datatable[1]
EXEC (@sqlstr)
print @sqlstr
--insert into a(a,remark) values(@sql,'list_cat')

--把#p中的数据根据品牌分组
set @sqlstr = 'select b.brandid,b.brandname,count(p.productid) as pnum from #p p(nolock) ,brand b(nolock) where p.brandid = b.brandid  and ' +  @where + 'group by b.brandid,b.brandname order by pnum desc'
--返回品牌分组datatable[2]
EXEC (@sqlstr)
print @sqlstr
--insert into a(a,remark) values(@sql,'list_brand')

if(len(@keyword) > 1 and @totalcount>0)--关键字不为单字符且记录数大于0才记录或更新关键字热度和搜索结果数
begin
	declare @keycount int
	select @keycount=count(id) from keyword where KeyWord = @keyword
	if(@keycount>0)--存在该关键字记录，更新热度及搜索结果
		begin
			update KeyWord set KeyHot = KeyHot+1,Records = @totalcount where KeyWord = @keyword
		end
	else
	begin
		insert KeyWord (KeyWord,Records) values (@keyword,@totalcount)
	end
end
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch

end











GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtSearchForRule_Get]    脚本日期: 04/09/2012 18:28:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-05-21>
-- Description:	<管理后台促销规则搜索商品>
-- Debug:
/*
declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
declare @key varchar(100),@cid varchar(20),@subcat varchar(20),@bid varchar(20),@pids varchar(2000),@productno varchar(20),@status int,@lowprice decimal(18,2),@highprice decimal(18,2),@lowstock int,@highstock int,@starttime varchar(50),@endtime varchar(50),@tag varchar(100),@supplierid int,@pagesize int,@pageno int
select @key='',@cid='-1',@subcat='-1',@bid='-1',@pids='',@productno='',@status=1,@lowPrice=0,@highprice=0,@lowstock=0,@highstock=0,@starttime='',@endtime='',@tag='',@supplierid=0,@pagesize=15,@pageno=1
exec XpProc_PdtSearch_Get @key,@cid,@subcat,@bid,@pids,@productno,@status,@lowPrice,@highprice,@lowstock,@highstock,@starttime,@endtime,@tag,@supplierid,@pagesize,@pageno,@totalpage output,@totalcount output,@errorflag output,@errormsg output
select @totalpage,@totalcount,@errorflag,@errormsg
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtSearchForRule_Get]
@pbegintime varchar(50)=null,--活动开始时间
@pendtime varchar(50)=null,--活动结束时间
@key varchar(100)=null,--关键字
@cid varchar(20)=null,--主分类
@subcat varchar(20)=null,--店内分类
@bid varchar(20)=null,--品牌ID
@pids varchar(2000)=null,--逗号分隔的商品ID字符串
@productno varchar(20)=null,--商品编号
@status int=null,--商品状态
@lowprice decimal(18,2)=null,--价格区间下限
@highprice decimal(18,2)=null,--价格区间上限
@lowstock int=null,--库存区间下限
@highstock int=null,--库存区间上限
@starttime varchar(50)=null,--添加时间下限
@endtime varchar(50)=null,--添加时间上线
@tag varchar(100)=null,--标签
@supplierid int=0,--商家ID
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@totalpage int output,--总页数
@totalcount int output,--总记录数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
--declare @totalpage int,@totalcount int,@errorflag int,@errormsg varchar(200)
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
select top 0 convert(int,0) as rowno,convert(int,0) as ruleid,convert(varchar(100),'') as rulename,convert(int,productid) as productid,productname,productno,categoryid,brandid,memberprice,productimg,imgfolder into #p from product
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' Isforsale=1 and isdel=0 and status=1 and supplierid = '+convert(varchar(20),@supplierid)

if isnull(@cid,-1)<>-1
select @where=@where+' and categoryno like '''+convert(varchar(50),dbo.f_GetCategoryNo(@cid))+'%'''

if isnull(@bid,-1)<>-1
select @where=@where+' and brandid = '+@bid

if isnull(@productno,'')<>''
select @where=@where+' and productno = '+@productno

if isnull(@status,9999)<>9999
select @where=@where+' and status = '+convert(varchar(10),@status)

if isnull(@lowprice,0)<>0
select @where=@where+' and memberprice >= '+convert(varchar(20),@lowprice)

if isnull(@highprice,0)<>0
select @where=@where+' and memberprice <= '+convert(varchar(20),@highprice)

if isnull(@lowstock,0)<>0
select @where=@where+' and storage >= '+convert(varchar(20),@lowstock)

if isnull(@highstock,0)<>0
select @where=@where+' and storage <= '+convert(varchar(20),@highstock)

if isnull(@starttime,'')<>''
select @where=@where+' and addtime >='+@starttime

if isnull(@endtime,'')<>''
select @where=@where+' and addtime <= '+@endtime

if isnull(@pids,'')<>''
select @where=@where+' and productid in (' + @pids + ')'

if isnull(@key,'')<>''
select @where=@where+' and productname like ''%' + @key + '%'''


select @sqlstr='insert into #p(ruleid,rulename,productid,productname,productno,categoryid,brandid,memberprice,productimg,imgfolder,rowno) select * from (
select 0 as ruleid,'''' as rulename,productid,productname,productno,categoryid,brandid,memberprice,productimg,imgfolder,Row_number() over(order by productid desc) as rowno 
from product(nolock)
where ' + @where + ') as p where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

--print @sqlstr
--insert into log(content) values(@sqlstr)
--select *from log order by addtime desc 
Execute(@sqlstr)
--获取该促销时间内已参加单品促销的商品
if isnull(@pbegintime,'')<>'' and isnull(@pendtime,'')<>''
begin
select productid,goodsid,ruleid,rulename into #r from PmtGoodsList(nolock) where ((endtime between @pbegintime and @pendtime) or (@pendtime between begintime and endtime)) and BasicType='goods' and SubType in('discount','specialprice','limittime')
update p set p.ruleid=r.ruleid,p.rulename=r.rulename from #p p,#r r where p.productid=r.productid
end
--返回商品
select * from #p
--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by productid desc) as rowno from product(nolock) where ' + @where + ') as p)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END













GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtSecKill_Get]    脚本日期: 04/09/2012 18:28:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-11-30>
-- Description:	<获取秒杀商品>
-- Debug:

-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtSecKill_Get]
@sid int=0--商家ID
AS
BEGIN
--获取秒杀商品
select top 2 p.productid,p.productname,g.pmtnumber,g.balance,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime,r.ruleid,r.ruleno,goodsid 
from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) 
where 
--datediff(day,getdate(),r.begintime)=0 
r.endtime>getdate()
and r.basictype='goods' 
and r.subtype='seckill' 
and r.supplierid=@sid
and g.ruleid=r.ruleid 
and g.productid=p.productid 
order by r.begintime asc
END


















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtSecKill_PageList_Get]    脚本日期: 04/09/2012 18:28:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-05-21>
-- Description:	<分页获取秒杀商品>
-- Debug:

-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtSecKill_PageList_Get]
--@cid varchar(20)='0',--主分类
@supplierid int=0,--商家ID
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@totalpage int output,--总页数
@totalcount int output,--总记录数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
--获取未过期的秒杀活动
select Row_number() over(order by begintime) as ruleindex,ruleid,ruleno,rulename,basictype,subtype,begintime,endtime into #r from pmtrule(nolock) where basictype='goods' and subtype='seckill' and endtime>getdate()
--select * from #r
--先创建一个公用的临时表
select top 0  g.productid,g.productname,g.pmtnumber,g.balance,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,r.ruleid,r.ruleno,goodsid,img1,i.sort 
into #temp
from product p(nolock),pmtgoods g(nolock),#r r(nolock),pdtimg i(nolock)

--构造条件
select @where = 'p.productid=i.pid and p.productid=g.productid and g.ruleid=r.ruleid and r.ruleindex=1'

--select @sqlstr='select rowno,productid,productname,pmtnumber,balance,(pmtnumber-balance)as alreadyjoin ,shortdesc,marketprice,memberprice,imgfolder,ThumbnailImg,productimg,img5,pmtprice,begintime,endtime,leavingday,ruleid,ruleno,goodsid,img1 from (
select @sqlstr='insert into #temp select productid,productname,pmtnumber,balance,shortdesc,marketprice,memberprice,imgfolder,ThumbnailImg,productimg,img5,pmtprice,begintime,endtime, datediff(d,getdate(),endtime) as leavingday,ruleid,ruleno,goodsid,img1,sort from(
select g.productid,g.productname,g.pmtnumber,g.balance,(pmtnumber-balance)as alreadyjoin ,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,r.ruleid,r.ruleno,goodsid,img1,i.sort,Row_number() over('
select @sqlstr=@sqlstr+'order by g.sort,g.addtime desc'
select @sqlstr=@sqlstr+ ') as rowno 
from product p(nolock),pmtgoods g(nolock),#r r(nolock),pdtimg i(nolock) where ' + @where + ') as a where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
--print @sqlstr
--insert log(content)values(@sqlstr)
Execute(@sqlstr)
--取得每个商品中对应的大图sort最小的图片
select* from #temp
where  not exists(select *from(select *from #temp)as b where #temp.productid=b.productid and #temp.sort>b.sort)
--获取总记录数和总页数
select @where='p.productid=g.productid and g.ruleid=r.ruleid and r.ruleindex=1'
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by g.id desc) as rowno from product p(nolock),pmtgoods g(nolock),#r r(nolock) where ' + @where + ') as l)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output
if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)

--获取预告秒杀期数
select r.ruleid,r.ruleno,r.rulename,r.basictype,r.subtype from #r r where ruleindex>1
--获取预告秒杀商品
select p.productid,p.productname,g.pmtnumber,g.balance,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,r.ruleid,r.ruleno,goodsid 
from product p(nolock),pmtgoods g(nolock),#r r(nolock) 
where g.ruleid=r.ruleid and g.productid=p.productid and r.ruleindex>1
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END























GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtSecKill_PageList_Get_bak]    脚本日期: 04/09/2012 18:28:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-05-21>
-- Description:	<分页获取秒杀商品>
-- Debug:

-- =============================================
create PROCEDURE [dbo].[XpProc_PdtSecKill_PageList_Get_bak]
--@cid varchar(20)='0',--主分类
@supplierid int=0,--商家ID
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@totalpage int output,--总页数
@totalcount int output,--总记录数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = 'p.productid=i.pid and p.productid=g.productid and g.ruleid=r.ruleid and g.basictype=''goods'' and g.subtype=''seckill'' and datediff(day,getdate(),r.begintime)=0'
--select @where = ' p.productid=g.productid and g.ruleid=r.ruleid and g.basictype=''goods'' and g.subtype=''seckill'' and getdate() between r.begintime and r.endtime'

--if isnull(@cid,'0')<>'0'
--select @where=@where+' and p.categoryno like '''+convert(varchar(50),dbo.f_GetCategoryNo(@cid))+'%'''

select top 0  g.productid,g.productname,g.pmtnumber,g.balance,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,r.ruleid,r.ruleno,goodsid,img1,i.sort 
into #temp
from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock),pdtimg i(nolock)

--select @sqlstr='select rowno,productid,productname,pmtnumber,balance,(pmtnumber-balance)as alreadyjoin ,shortdesc,marketprice,memberprice,imgfolder,ThumbnailImg,productimg,img5,pmtprice,begintime,endtime,leavingday,ruleid,ruleno,goodsid,img1 from (
select @sqlstr='insert into #temp select productid,productname,pmtnumber,balance,shortdesc,marketprice,memberprice,imgfolder,ThumbnailImg,productimg,img5,pmtprice,begintime,endtime, datediff(d,getdate(),endtime) as leavingday,ruleid,ruleno,goodsid,img1,sort from(
select g.productid,g.productname,g.pmtnumber,g.balance,(pmtnumber-balance)as alreadyjoin ,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,r.ruleid,r.ruleno,goodsid,img1,i.sort,Row_number() over('
select @sqlstr=@sqlstr+'order by g.sort,g.addtime desc'
select @sqlstr=@sqlstr+ ') as rowno 
from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock),pdtimg i(nolock) where ' + @where + ') as a where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
--print @sqlstr
--insert log(content)values(@sqlstr)
Execute(@sqlstr)
--取得每个商品中对应的大图sort最小的图片
select* from #temp
where  not exists(select *from(select *from #temp)as b where #temp.productid=b.productid and #temp.sort>b.sort)
--获取总记录数和总页数
select @where='p.productid=g.productid and g.ruleid=r.ruleid and g.basictype=''goods'' and g.subtype=''seckill'' and datediff(day,getdate(),r.begintime)=0'
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by g.id desc) as rowno from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) where ' + @where + ') as l)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)

--获取预告秒杀期数
select r.ruleid,r.ruleno,r.rulename,r.basictype,r.subtype from pmtrule r(nolock) where datediff(day,getdate(),r.begintime)>0 and r.basictype='goods' and r.subtype='seckill'
--获取预告秒杀商品
select p.productid,p.productname,g.pmtnumber,g.balance,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,r.ruleid,r.ruleno,goodsid from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) where datediff(day,getdate(),r.begintime)>0 and r.basictype='goods' and r.subtype='seckill' and g.ruleid=r.ruleid and g.productid=p.productid 
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END























GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtSkumap_Update]    脚本日期: 04/09/2012 18:28:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[XpProc_PdtSkumap_Update](
@pid int=null--商品id
)
as
begin
begin tran
declare @productid int 
declare products_items_cursor cursor for
select productid from product
where productid=case when @pid is null then productid else @pid end
--skumap is not null
order by productid 
open products_items_cursor
fetch next from products_items_cursor into
@productid
while @@fetch_status=0
begin
	--构造SkuMap并更新到商品表
	declare @skumap varchar(8000),@propid varchar(50),@goodsid int,@goodsprice decimal(18,2),@goodsstock int,@goodsno varchar(50)
	--定义遍历当前商品的不同规格的货品的游标
	declare goods_items_cursor cursor for                                                    
	select goodsid,goodsno,memberprice,storage,isnull(props,'0:0;0:0')
	from goods
	where productid=@productid
	order by goodsid asc
	select @skumap='{'
	--遍历游标
	open goods_items_cursor                                                    
	fetch next from goods_items_cursor into 
	@goodsid,@goodsno,@goodsprice,@goodsstock,@propid
    while @@fetch_status = 0                        
	begin 
	select @skumap=@skumap+'"'+@propid+'":{"skuId":"'+cast(@goodsid as varchar(50))+'","price":"'+cast(@goodsprice as varchar(50))+'","stock":"'+cast(@goodsstock as varchar(50))+'","code":"'+@goodsno+'"},'
	fetch next from goods_items_cursor into 
	@goodsid,@goodsno,@goodsprice,@goodsstock,@propid
	end
	set @skumap=STUFF(@skumap,len(@skumap),1,'}')
	update product set skumap=@skumap where productid=@productid
--	insert log(content)values(@skumap)
	--select *From log order by id 
	--遍历结束
	close goods_items_cursor                                                    
	deallocate goods_items_cursor
	fetch next from products_items_cursor into @productid
end                                           
close products_items_cursor   
deallocate products_items_cursor
commit tran
end



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtStatus_Update]    脚本日期: 04/09/2012 18:28:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-08-20>
-- Description:	<更新商品的二种种状态,isforsale,status>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtStatus_Update] (
@pid int,--商品ID
--@productname nvarchar(255)=null,
@name varchar(100), --商品表中要更新的字段
@value int,--更新的字段的值
@memberid int ,--会员ID
@memberName nvarchar(100)=null,--会员名称
@ip nvarchar(40),
@errorFlag int=0 output,
@errorMsg varchar(100)=null output
)
AS
Begin
select @errorFlag=1
begin try
begin tran
declare @RootCatID int,@SubCatID int,@description nvarchar(255),@productname nvarchar(255)
declare @isModify bit--是否记录日志，只有改变了商品的状态才要写日志
select @productname=productname from product(nolock) where productid=@pid
select @isModify=0 --是否要更新商品的状态，0为否，1为是

--商品上下架
if(@name='IsForSale')
begin
	declare @oldIsForSale int --原来的状态
	select @oldIsForSale=IsForSale from product(nolock)where  productid=@pid
	if(@value=0 and @oldIsForSale<>0)--商品下架
	begin
		select @isModify=1
		select @RootCatID=5
		select @SubCatID=52
		select @description='商品下架:'+@productname
		--删除购物车中的相关商品
		DELETE FROM ShoppingCart WHERE ProductID=@pid
	end
	else if(@value=1 and @oldIsForSale<>1)
	begin
		select @isModify=1
		select @RootCatID=5
		select @SubCatID=51
		select @description='商品上架:'+@productname
	end
	--更新商品的状态
	if(@isModify=1)
	update product set IsForSale=@value,updatetime=getDate() where productid=@pid
end
--商品的审核
else if(@name='status')
begin
	declare @oldStatus int --原来的状态
	select @oldStatus=status from product(nolock)where  productid=@pid
	if(@value=0 and @oldStatus<>0)--未审核
	begin
		select @isModify=1
		select @RootCatID=5
		select @SubCatID=54
		select @description='商品未审核:'+@productname
		--删除购物车中的相关商品
		DELETE FROM ShoppingCart WHERE ProductID=@pid
	end
	else if(@value=1 and @oldStatus<>1)--已审核
	begin
		select @isModify=1
		select @RootCatID=5
		select @SubCatID=54
		select @description='商品已审核:'+@productname
	end
	else if(@value=-1 and @oldStatus<>-1)
	begin
		select @isModify=1
		select @RootCatID=5
		select @SubCatID=54
		select @description='商品审核未通过:'+@productname
		--删除购物车中的相关商品
		DELETE FROM ShoppingCart WHERE ProductID=@pid
	end
	--更新商品的状态
	if(@isModify=1)
	update product set status=@value,updatetime=getDate() where productid=@pid
end

if(@isModify=1)
begin
--写日志
exec XpProc_Eventlog_Insert @memberid,@membername,'',@RootCatID,@SubCatID,@description,@ip
end
select @errorFlag=0
commit tran
end try

begin catch
	select @errorFlag=1
	select @errormsg=error_Message()
	rollback
end catch
end



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtTag_Add]    脚本日期: 04/09/2012 18:28:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-08-15>
-- Description:	<添加标签商品>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtTag_Add]
@tagid int,--标签ID
@ishomeshow bit,--是否首页显示
@pids varchar(8000),--逗号分隔的商品ID字符串
@cids varchar(8000),--逗号分隔的分类ID字符串
@sorts varchar(8000),--逗号分隔的排序序号字符串
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
Begin Try
select * into #p from SplitToTable_Func(@pids,',')
select * into #c from SplitToTable_Func(@cids,',')
select * into #s from SplitToTable_Func(@sorts,',')

select p.value as productid,tagid=@tagid,ishomeshow=@ishomeshow,c.value as categoryid,g.categoryno,s.value as sort
into #t
from #p p,#c c,#s s,category g(nolock)
where p.id=c.id and p.id=s.id and c.value=g.categoryid

insert into pdttag(productid,tagid,ishomeshow,categoryid,categoryno,sort) select * from #t
select @errorflag=0,@errormsg=''
End Try

Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
insert into log(content) values(@errormsg)
Return
End Catch
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtTag_Get]    脚本日期: 04/09/2012 18:28:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-08-15>
-- Description:	<获取标签商品>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtTag_Get]
@cids varchar(8000),--逗号分隔的分类ID字符串
@tagid int,--标签ID
@num int,--商品数量
@ishomeshow bit --是否首页显示
AS
BEGIN
select * into #c from SplitToTable_Func(@cids,',')

select g.categoryid,g.categoryno
into #cc
from #c c,category g(nolock)
where c.value=g.categoryid

select top (@num)
p.ProductID,ProductName,p.CategoryNo,ProductNo,BrandName,ShortDesc,MarketPrice,Score,MemberPrice,ThumbnailImg,ProductImg,ImgFolder,Img5 
FROM Product p(nolock),PdtTag t(nolock),#cc c(nolock)
Where t.tagid=@tagid and t.ishomeshow=@ishomeshow and c.categoryno=left(t.categoryno,len(c.categoryno)) and t.ProductID = p.ProductID and Status > 0 and IsForSale = 1 and isdel=0
order by t.sort desc
END





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PdtTopSale_Get]    脚本日期: 04/09/2012 18:28:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-09-23>
-- Description:	<获取销售排行商品>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PdtTopSale_Get] 
@cid int,--分类ID
@num int,--获取的数量
@catname varchar(50) output --输出分类名称
AS
BEGIN
declare @categoryno varchar(50)
select @catname=[name],@categoryno=categoryno from category where categoryid=@cid

select top (@num) p.ProductID,ProductName,ProductNo,BrandName,ImgFolder,MarketPrice,MemberPrice,ProductImg,ThumbnailImg,isnull(t.Sort,99999999) as sort ,Img5,ShortDesc,salenum,p.categoryid,p.unit
from product p(nolock)
left join topsale t on (t.productid = p.productid and t.CategoryID=case when @cid=0 then t.CategoryID else @cid end) 
where isforsale=1 and status=1 and p.categoryno like @categoryno+'%'
order by sort,p.SaleNum desc
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtGoods_Get]    脚本日期: 04/09/2012 18:28:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-16>
-- Description:	<得到特定类型的促销商品>
-- Debug:
/*
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PmtGoods_Get]
	@type int=null,--促销商品的类型 1是限时抢购 2是秒杀 3 团购
	@top int=10,--页大小
	@status int --0活动没有开始，1活动正在进行 2已经结束
AS
begin
set nocount on
declare @sqlstr varchar(8000)--查询
declare @where varchar(1024) --查询条件
set @where =' g.IsHomeShow=1 and g.ruleid=r.ruleid and p.productid=g.productid and   '

if isnull(@type,0)<>0
begin
declare @temp varchar(200)
select @temp=case @type when 1 then 'g.subtype=''limittime''' when 2 then 'g.subtype=''seckill''' when 3 then 'g.subtype=''tuangou''' end
set @where=@where+@temp
end

if @status is not null
begin
select @temp=case @status when 0 then  ' and r.begintime>getDate()'  when 1 then ' and getdate() between r.begintime and r.endtime' when 2 then ' and r.endtime<getDate()' end
set @where=@where+@temp
end

select @sqlstr='select top '+cast(@top as varchar(2))+' g.pmtprice, g.ID,g.productname,p.imgfolder,p.ThumbnailImg 
from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) 
where '+@where

Execute(@sqlstr)
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtGoodsRelateInfo_Get]    脚本日期: 04/09/2012 18:28:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-10>
-- Description:	<获取促销商品有关信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PmtGoodsRelateInfo_Get]
@ruleid int ,
@pageSize int =16,--每页显示
@pageNo int=1,--页码
@basictype  varchar(100)=null,
@subtype varchar(100)=null,
@totalpage int=null output,--总页数
@totalcount int=null output,--总记录数
@errorflag int=null output,
@errormsg varchar(200)=null output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' pr.ruleid=pg.ruleid and pg.goodsid=g.goodsid and g.productid=p.productid '

if isnull(@ruleid,0)<>0
select @where=@where+' and pg.ruleid='+convert(varchar(20),@ruleid)

select @sqlstr='select * from (
select pg.ID,pg.GoodsID,pg.ProductName,PmtPrice,cast(minvalue as int)as MinValue,cast(maxvalue as int)as MaxValue,(PmtNumber-Balance) as Purchased,pg.RuleName,GroupIDs as Grade,pr.BeginTime,
pr.EndTime,ProductImg,ImgFolder,Balance,Row_number() over(order by id desc) as rowno
from pmtrule pr(nolock),pmtgoods pg(nolock),product p(nolock),goods g(nolock) where '+@where+')as temp 
where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
--获取分页商品datatable[1]
--insert log(content)values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by pg.ruleid desc) as rowno from pmtrule pr(nolock),pmtgoods pg(nolock),product p(nolock),goods g(nolock) where '+@where+')as temp)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output
select @totalcount=isnull(@totalcount,0)
select @totalpage=ceiling(@totalcount*1.0 / @pagesize)
end








GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtList_Insert]    脚本日期: 04/09/2012 18:28:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-05-20>
-- Description:	<添加促销活动>
/*
引用该存储过程的存储过程：
1、XpProc_PmtRule_LimitTime_Insert
2、XpProc_PmtRule_CouponIssue_Insert
*/
-- =============================================
CREATE PROC [dbo].[XpProc_PmtList_Insert]
	@PmtName nvarchar(200) = NULL,
	@BeginTime datetime,
	@EndTime datetime,
	@Description nvarchar(2000) = NULL,
	--@PmtType nvarchar(200) = NULL,
	@AddTime datetime = NULL,
	@AddUser int = NULL,
	@AddUserName nvarchar(100) = NULL,
	@Status int = NULL,
	--@UpdateTime datetime = NULL,
	--@UpdateUser int = NULL,
	--@UpdateUserName nvarchar(100) = NULL,
	--@UpdateHistory nvarchar(1600) = NULL,
	--@Auditor int = NULL,
	--@AuditorName nvarchar(100) = NULL,
	--@AuditTime datetime = NULL,
	@Remark nvarchar(200) = NULL,
	--@IsCanUsedCoupon tinyint = NULL,
	@SupplierID int = NULL
AS

INSERT pmtlist(
PmtName, BeginTime, EndTime, Description, AddUser, AddUserName, Status, SupplierID, AddTime
--PmtType, UpdateTime, UpdateUser, UpdateUserName, UpdateHistory, Auditor, AuditorName, AuditTime, Remark, IsCanUsedCoupon
)
VALUES (
@PmtName, @BeginTime, @EndTime, @Description, @AddUser, @AddUserName, COALESCE(@Status, (0)), COALESCE(@SupplierID, (0)), COALESCE(@AddTime, getdate())
--@PmtType, @UpdateTime, @UpdateUser, @UpdateUserName, @UpdateHistory, @Auditor, @AuditorName, @AuditTime, @Remark, COALESCE(@IsCanUsedCoupon, (0))
)
RETURN SCOPE_IDENTITY()





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtList_Update]    脚本日期: 04/09/2012 18:28:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-05-20>
-- Description:	<添加促销活动>
-- =============================================
CREATE PROC [dbo].[XpProc_PmtList_Update]
	@PmtID int,
	@PmtName nvarchar(200) = NULL,
	@BeginTime datetime,
	@EndTime datetime,
	@Description nvarchar(2000) = NULL,
	--@PmtType nvarchar(200) = NULL,
	--@AddTime datetime = NULL,
	--@AddUser int = NULL,
	--@AddUserName nvarchar(100) = NULL,
	@Status int,
	@UpdateTime datetime = NULL,
	@UpdateUser int = NULL,
	@UpdateUserName nvarchar(100) = NULL,
	--@UpdateHistory nvarchar(1600) = NULL,
	--@Auditor int = NULL,
	--@AuditorName nvarchar(100) = NULL,
	--@AuditTime datetime = NULL,
	@Remark nvarchar(200) = NULL,
	@IsCanUsedCoupon tinyint = null
	--@SupplierID int = null
AS

UPDATE	pmtlist
SET	PmtName = @PmtName,
	BeginTime = @BeginTime,
	EndTime = @EndTime,
	Description = @Description,
	--PmtType = @PmtType,
	--AddTime = COALESCE(@AddTime, getdate()),
	--AddUser = @AddUser,
	--AddUserName = @AddUserName,
	Status = COALESCE(@Status, (0)),
	UpdateTime = COALESCE(@UpdateTime, getdate()),
	UpdateUser = @UpdateUser,
	UpdateUserName = @UpdateUserName,
	--UpdateHistory = @UpdateHistory,
	--Auditor = @Auditor,
	--AuditorName = @AuditorName,
	--AuditTime = @AuditTime,
	Remark = @Remark,
	IsCanUsedCoupon = COALESCE(@IsCanUsedCoupon, (0))
	--SupplierID = COALESCE(@SupplierID, (0))
WHERE 	PmtID = @PmtID





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtRule_CouponIssue_Insert]    脚本日期: 04/09/2012 18:28:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-10-09>
-- Description:	<添加优惠券派发促销规则>

/*
modify history:   
version:v1.1   
author:hakkas@qq.com                                
time:20111122                              
content:                                
1.增加参数@RuleAD用于促销广告功能                      
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PmtRule_CouponIssue_Insert] 
@RuleName varchar(100) = NULL,
@RuleNo varchar(50) = NULL,
@PmtID int = NULL,
@PmtType varchar(20)=NULL,
@PmtTypeName varchar(50)=null,
@BasicType varchar(50) = 'register',
@SubType varchar(50) = 'coupon',
@BeginTime datetime = NULL,
@EndTime datetime = NULL,
@Discount decimal(18, 2) = 1,
@LessMoney money = 0,
@MinValue money = 0,
@MaxValue money = 0,
@IsAutoAdded int = 0,
@GroupIDs varchar(50) = NULL,
@AddTime datetime = NULL,
@AddUser int = NULL,
@AddUserName varchar(50) = NULL,
@Status int = NULL,
@Remark varchar(100) = NULL,
@SupplierID int = NULL,
@pids varchar(8000)=null,--逗号分隔的商品ID字符串
@cids varchar(8000)=null,--逗号分隔的优惠券ID字符串
@validitys varchar(8000)=null,--逗号分隔的优惠券有效天数
@nums varchar(8000)=null,--逗号分隔的优惠券数量字符串
@RuleAD varchar(1000)=null,--促销广告
@errorFlag int output,
@errorMsg varchar(200) output
AS
BEGIN
Begin Try
select @SupplierID=COALESCE(@SupplierID, (0))
select @AddTime=COALESCE(@AddTime, getdate())

--没有活动要先插入活动记录
if isnull(@PmtID,-1)=-1
exec @PmtID=XpProc_PmtList_Insert @RuleName,@BeginTime,@EndTime,@Remark,@AddTime,@AddUser,@AddUserName,1,@Remark,@SupplierID

--插入规则
declare @ruleid int
exec @ruleid=XpProc_PmtRule_Insert @RuleName,@RuleNo,@PmtID,@PmtType,@PmtTypeName,@BasicType, @SubType,@BeginTime,@EndTime, @Discount, @LessMoney, @MinValue, @MaxValue,@IsAutoAdded, @GroupIDs,@AddTime, @AddUser, @AddUserName,@Status,@remark,@SupplierID,0,null,null,@RuleAD

--单品返券要插入促销商品
if @BasicType='goods' and @SubType='coupon'
begin
select * into #p1 from SplitToTable_Func(@pids,',')

select pmtname=@rulename,pmtid=@PmtID,ruleid=@ruleid,rulename=@rulename,basictype=@BasicType,subtype=@SubType,
productid=p1.value,productname=p.productname,categoryid=p.categoryid,brandid=p.brandid,brandname=p.brandname,
marketprice=p.marketprice,memberprice=p.memberprice,
/*
pmtprice=p2.value,
pmtnumber=case when isnull(p5.value,'')='' then 0 when isnull(p5.value,'0')='0' then 0 else p5.value end,
Balance=case when isnull(p5.value,'')='' then 0 when isnull(p5.value,'0')='0' then 0 else p5.value end,
LimitedNumber=case when isnull(p3.value,'')='' then 0 when isnull(p3.value,'0')='0' then 0 else p3.value end,
IsLimited=case when isnull(p3.value,'')='' then 0 when isnull(p3.value,'0')='0' then 0 else 1 end,
*/
addtime=@AddTime,adduser=@adduser,addusername=@addusername,status=COALESCE(@Status, (1)),SupplierID=@SupplierID,IsHomeShow=0
into #p
from #p1 p1,product p(nolock)
where p1.value=p.productid

insert into pmtgoods(pmtname,pmtid,ruleid,rulename,basictype,subtype,productid,productname,categoryid,brandid,
brandname,marketprice,memberprice,
--pmtprice,pmtnumber,Balance,LimitedNumber,IsLimited,
addtime,adduser,addusername,status,SupplierID,IsHomeShow) 
select * from #p
end

--插入派发优惠券
select * into #c1 from SplitToTable_Func(@cids,',')
select * into #n from SplitToTable_Func(@nums,',')
select * into #v from SplitToTable_Func(@validitys,',')

select pmtid=@PmtID,pmtname=@rulename,ruleid=@ruleid,rulename=@rulename,basictype=@BasicType,subtype=@SubType,
c1.value as couponid,c.couponname as couponname,v.value as validity,n.value as number,balance=0,limitednumber=1,islimited=0,@remark as remark,addtime=@AddTime,
adduser=@adduser,addusername=@addusername,status=COALESCE(@Status, (1)),SupplierID=@SupplierID
into #c
from #c1 c1,#n n,#v v,coupon c(nolock)
where c1.id=n.id and c1.id=v.id and c1.value=c.couponid

insert into pmtcoupons(pmtid,pmtname,ruleid,rulename,basictype,subtype,couponid,couponname,validity,number,balance,
limitednumber,islimited,remark,addtime,adduser,addusername,status,supplierid)
select * from #c

select @errorflag=0
select @errormsg=''

RETURN SCOPE_IDENTITY()
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return 0
End Catch	
END






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtRule_CouponIssue_RelatedInfo_Get]    脚本日期: 04/09/2012 18:28:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-10-10>
-- Description:	<获取优惠券派发促销规则相关信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PmtRule_CouponIssue_RelatedInfo_Get]
@ruleid int, --规则ID
@pids varchar(8000) output,--用逗号分隔的促销商品的ID
@cids varchar(8000) output--用逗号分隔的优惠券的ID
AS
BEGIN
--获取促销规则基本信息
select pmtid,rulename,begintime,endtime,GroupIDs,MinValue,MaxValue,Remark from pmtrule(nolock) where ruleid=@ruleid

--获取促销规则相关优惠券信息
select c.CouponID,c.CouponName,c.CouponValue,isnull(p.number,1) as PmtNumber, case when isnull(p.number,0)=0 then 0 else 1 end as IsSelected,p.Validity
from coupon c(nolock)
left join pmtcoupons p(nolock) on p.ruleid=@ruleid and p.couponid=c.couponid
where getdate()<c.EndTime and c.status=1

select @pids='' 
select @pids=@pids+','+cast(productid as varchar) from pmtgoods where ruleid=@ruleid
select @pids=stuff(@pids,1,1,'')

select @cids='' 
select @cids=@cids+','+cast(couponid as varchar) from pmtcoupons where ruleid=@ruleid
select @cids=stuff(@cids,1,1,'')
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtRule_CouponIssue_Update]    脚本日期: 04/09/2012 18:28:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-10-09>
-- Description:	<更新优惠券派发方式促销规则>

/*
modify history:   
version:v1.1   
author:hakkas@qq.com                                
time:20111122                              
content:                                
1.增加参数@RuleAD用于促销广告功能                      
*/
-- =============================================
CREATE PROC [dbo].[XpProc_PmtRule_CouponIssue_Update]
@RuleID int,
@RuleName varchar(100) = NULL,
@PmtID int = NULL,
@RuleNo varchar(50) = NULL,
@PmtType varchar(20)=NULL,
@PmtTypeName varchar(50)=null,
@BasicType varchar(50) = 'register',
@SubType varchar(50) = 'coupon',
@BeginTime datetime = NULL,
@EndTime datetime = NULL,
@Discount decimal(18, 2) = 1,
@LessMoney money = 0,
@MinValue money = 0,
@MaxValue money = 0,
@IsAutoAdded int = 0,
@GroupIDs varchar(50) = NULL,
@UpdateTime datetime = NULL,
@UpdateUser int = NULL,
@UpdateUserName varchar(50) = NULL,
@Status int = NULL,
@Remark varchar(100) = NULL,
@SupplierID int = NULL,
--@ids varchar(8000)=null,
@pids varchar(8000)=null,--逗号分隔的商品ID字符串
@cids varchar(8000)=null,--逗号分隔的优惠券ID字符串
@validitys varchar(8000)=null,--逗号分隔的优惠券有效天数
@nums varchar(8000)=null,--逗号分隔的优惠券数量字符串
@RuleAD varchar(1000)=null,--促销广告
@errorFlag int output,
@errorMsg varchar(200) output
AS
begin
Begin Try
select @SupplierID=COALESCE(@SupplierID, (0))
select @UpdateTime=COALESCE(@UpdateTime, getdate())

--更新活动
exec XpProc_PmtList_Update @PmtID,@RuleName,@BeginTime,@EndTime,@Remark,@Status,@UpdateTime,@UpdateUser,@UpdateUserName,@Remark,0

--更新规则
exec XpProc_PmtRule_Update @RuleID,@RuleName,@RuleNo,@PmtType,@PmtTypeName,@BasicType, @SubType,@BeginTime,@EndTime, @Discount, @LessMoney, @MinValue, @MaxValue,@IsAutoAdded, @GroupIDs,@UpdateTime,@UpdateUser,@UpdateUserName,@Status,@remark,@SupplierID,0,null,null,@RuleAD

--清空就的促销商品和促销优惠券
delete from pmtgoods where ruleid=@ruleid
delete from pmtcoupons where ruleid=@ruleid

--单品返券要插入促销商品
if @BasicType='goods' and @SubType='coupon'
begin
select * into #p1 from SplitToTable_Func(@pids,',')

select pmtname=@rulename,pmtid=@PmtID,ruleid=@ruleid,rulename=@rulename,basictype=@BasicType,subtype=@SubType,
productid=p1.value,productname=p.productname,categoryid=p.categoryid,brandid=p.brandid,brandname=p.brandname,
marketprice=p.marketprice,memberprice=p.memberprice,
/*
pmtprice=p2.value,
pmtnumber=case when isnull(p5.value,'')='' then 0 when isnull(p5.value,'0')='0' then 0 else p5.value end,
Balance=case when isnull(p5.value,'')='' then 0 when isnull(p5.value,'0')='0' then 0 else p5.value end,
LimitedNumber=case when isnull(p3.value,'')='' then 0 when isnull(p3.value,'0')='0' then 0 else p3.value end,
IsLimited=case when isnull(p3.value,'')='' then 0 when isnull(p3.value,'0')='0' then 0 else 1 end,
*/
addtime=@UpdateTime,adduser=@UpdateUser,addusername=@updateusername,status=COALESCE(@Status, (1)),SupplierID=@SupplierID,IsHomeShow=0
into #p
from #p1 p1,product p(nolock)
where p1.value=p.productid

insert into pmtgoods(pmtname,pmtid,ruleid,rulename,basictype,subtype,productid,productname,categoryid,brandid,
brandname,marketprice,memberprice,
--pmtprice,pmtnumber,Balance,LimitedNumber,IsLimited,
addtime,adduser,addusername,status,SupplierID,IsHomeShow) 
select * from #p
end

--插入派发优惠券
select * into #c1 from SplitToTable_Func(@cids,',')
select * into #n from SplitToTable_Func(@nums,',')
select * into #v from SplitToTable_Func(@validitys,',')

select pmtid=@PmtID,pmtname=@rulename,ruleid=@ruleid,rulename=@rulename,basictype=@BasicType,subtype=@SubType,
c1.value as couponid,c.couponname as couponname,v.value as validity,n.value as number,balance=0,limitednumber=1,islimited=0,@remark as remark,addtime=@UpdateTime,
adduser=@updateuser,addusername=@updateusername,status=COALESCE(@Status, (1)),SupplierID=@SupplierID
into #c
from #c1 c1,#n n,#v v,coupon c(nolock)
where c1.id=n.id and c1.id=v.id and c1.value=c.couponid

insert into pmtcoupons(pmtid,pmtname,ruleid,rulename,basictype,subtype,couponid,couponname,validity,number,balance,
limitednumber,islimited,remark,addtime,adduser,addusername,status,supplierid)
select * from #c

select @errorflag=0
select @errormsg=''

RETURN SCOPE_IDENTITY()
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return 0
End Catch

end







GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtRule_Delete]    脚本日期: 04/09/2012 18:28:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-10-09>
-- Description:	<删除促销规则>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PmtRule_Delete]
@ruleid varchar(8000),--逗号分隔的促销规则ID
@errorflag int out,--错误标志
@errormsg varchar(200) out--错误信息描述
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
begin tran
select * into #r from SplitToTable_Func(@ruleid,',')
--删除促销规则对应的优惠券
delete c from pmtcoupons c(nolock),#r r where c.ruleid=r.value
--删除促销规则对应的礼品
delete g from pmtgifts g(nolock),#r r where g.ruleid=r.value
--删除促销规则对应的商品
delete g from pmtgoods g(nolock),#r r where g.ruleid=r.value
--删除促销规则
delete g from pmtrule g(nolock),#r r where g.ruleid=r.value
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtRule_Insert]    脚本日期: 04/09/2012 18:28:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-05-20>
-- Description:	<更新促销规则>
/*
引用该存储过程的存储过程：
1、XpProc_PmtRule_LimitTime_Insert
2、XpProc_PmtRule_CouponIssue_Insert
*/
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110722                              
content:                                
1.添加是否首页显示功能  

version:v1.2   
author:hakkas@qq.com                                
time:20110726                              
content:                                
1.添加银行编号功能 1:中国银行;2:工商银行;3:建设银行;4:农业银行;5:招商银行;6:交通银行;7:光大银行  

version:v1.3   
author:hakkas@qq.com                                
time:20111122                              
content:                                
1.添加促销广告功能                     
*/
-- =============================================
CREATE PROC [dbo].[XpProc_PmtRule_Insert]
	@RuleName varchar(100) = NULL,
	@RuleNo varchar(50) = NULL,
	@PmtID int = NULL,
	@PmtType varchar(20)=null,
	@PmtTypeName varchar(50)=null,
	@BasicType varchar(50) = NULL,
	@SubType varchar(50) = NULL,
	@BeginTime datetime = NULL,
	@EndTime datetime = NULL,
	@Discount decimal(18, 2) = NULL,
	@LessMoney money = NULL,
	@MinValue money = NULL,
	@MaxValue money = NULL,
	@IsAutoAdded int = NULL,
	--@Condition varchar(100) = NULL,
	@GroupIDs varchar(50) = NULL,
	@AddTime datetime = NULL,
	@AddUser int = NULL,
	@AddUserName varchar(50) = NULL,
	@Status int = NULL,
/*
	@UpdateTime datetime = NULL,
	@UpdateUser int = NULL,
	@UpdateUserName varchar(50) = NULL,
	@UpdateHistory varchar(800) = NULL,
	@Auditor int = NULL,
	@AuditorName varchar(50) = NULL,
	@AuditTime datetime = NULL,	
*/
	@Remark varchar(100) = NULL,
	@SupplierID int = NULL,
	@CanUseCoupon bit = NULL,
	@IsHomeShow bit = NULL,
	@BankNo varchar(10)=-1,
	@RuleAD varchar(1000)=NULL --促销广告内容
AS
begin
INSERT pmtrule(
RuleName,RuleNo,PmtID, BasicType, SubType,BeginTime,EndTime, Discount, LessMoney, MinValue, MaxValue,IsAutoAdded,GroupIDs,  --1
AddTime, AddUser, AddUserName,Status, SupplierID,CanUseCoupon,PmtType,PmtTypeName,IsHomeShow,BankNo,RuleAD --2
--Condition,UpdateUserName,UpdateTime, UpdateUser, UpdateHistory, Auditor, AuditorName, AuditTime, Remark  --3
)
VALUES (
@RuleName,@RuleNo,@PmtID, @BasicType, @SubType,@BeginTime,@EndTime, @Discount, @LessMoney, @MinValue, @MaxValue,@IsAutoAdded, @GroupIDs, --1
COALESCE(@AddTime, getdate()), @AddUser, @AddUserName, COALESCE(@Status, (1)),COALESCE(@SupplierID, (0)),COALESCE(@CanUseCoupon, (0)),@PmtType,@PmtTypeName,COALESCE(@IsHomeShow, (1)),COALESCE(@BankNo, ('-1')),@RuleAD --2
--@Condition,@UpdateUserName, @UpdateTime, @UpdateUser, @UpdateHistory, @Auditor, @AuditorName, @AuditTime, @Remark --3
)

RETURN SCOPE_IDENTITY()

end




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtRule_LimitTime_Insert]    脚本日期: 04/09/2012 18:28:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-05-20>
-- Description:	<添加促销规则>
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110722                              
content:                                
1.添加是否首页显示功能   

modify history:  
version:v1.2   
author:hakkas@qq.com                                
time:20111122                              
content:                                
1.增加参数@RuleAD用于促销广告功能                      
*/
-- =============================================
CREATE PROC [dbo].[XpProc_PmtRule_LimitTime_Insert]
	@RuleName varchar(100) = NULL,
	@PmtID int = NULL,
	@RuleNo varchar(50) = NULL,
	@PmtType varchar(20)=null,
	@PmtTypeName varchar(50)=null,
	@BasicType varchar(50) = 'goods',
	@SubType varchar(50) = 'limittime',
	@BeginTime datetime = NULL,
	@EndTime datetime = NULL,
	@Discount decimal(18, 2) = 1,
	@LessMoney money = 0,
	@MinValue money = 0,
	@MaxValue money = 0,
	@IsAutoAdded int = 0,
	--@Condition varchar(100) = NULL,
	@GroupIDs varchar(50) = NULL,
	@AddTime datetime = NULL,
	@AddUser int = NULL,
	@AddUserName varchar(50) = NULL,
	@Status int = NULL,
	@Remark varchar(100) = NULL,
	@SupplierID int = NULL,
	@CanUseCoupon bit = NULL,
	@IsHomeShow bit = NULL,--是否首页显示
	@BankNo varchar(10),--银行编号
	@pids varchar(8000)=null,
	@pmtprices varchar(8000)=null,
	@pmtnums varchar(8000)=null,
	@limitnums varchar(8000)=null,
	@sorts varchar(8000)=null,
	@gids varchar(8000)=null,--秒杀功能用到
	@RuleAD varchar(1000)=NULL,--促销广告
	@errorFlag int output,
	@errorMsg varchar(200) output
AS
begin
Begin Try

select @SupplierID=COALESCE(@SupplierID, (0))
select @AddTime=COALESCE(@AddTime, getdate())
--没有活动要先插入活动记录
if isnull(@PmtID,-1)=-1
exec @PmtID=XpProc_PmtList_Insert @RuleName,@BeginTime,@EndTime,@Remark,@AddTime,@AddUser,@AddUserName,1,@Remark,@SupplierID

--插入规则
declare @ruleid int
exec @ruleid=XpProc_PmtRule_Insert @RuleName,@RuleNo,@PmtID,@PmtType,@PmtTypeName,@BasicType, @SubType,@BeginTime,@EndTime, @Discount, @LessMoney, @MinValue, @MaxValue,@IsAutoAdded, @GroupIDs,@AddTime, @AddUser, @AddUserName,@Status,@remark,@SupplierID,@CanUseCoupon,@IsHomeShow,@BankNo,@RuleAD
/*
INSERT pmtrule(
RuleName, PmtID, RuleNo, BasicType, SubType,BeginTime,EndTime, Discount, LessMoney, MinValue, MaxValue,IsAutoAdded,GroupIDs,  --1
AddTime, AddUser, AddUserName,Status, SupplierID,CanUseCoupon --2
--Condition,UpdateUserName,UpdateTime, UpdateUser, UpdateHistory, Auditor, AuditorName, AuditTime, Remark  --3
)
VALUES (
@RuleName, @PmtID, @RuleNo, @BasicType, @SubType,@BeginTime,@EndTime, @Discount, @LessMoney, @MinValue, @MaxValue,@IsAutoAdded, @GroupIDs, --1
@AddTime, @AddUser, @AddUserName, COALESCE(@Status, (1)),@SupplierID,COALESCE(@CanUseCoupon, (0)) --2
--@Condition,@UpdateUserName, @UpdateTime, @UpdateUser, @UpdateHistory, @Auditor, @AuditorName, @AuditTime, @Remark --3
)
declare @ruleid int
select @ruleid=@@identity
*/

--插入促销商品
select * into #p1 from dbo.SplitToTable_Func(@pids,',')
select * into #p2 from dbo.SplitToTable_Func(@pmtprices,',')
select * into #p3 from dbo.SplitToTable_Func(@limitnums,',')
select * into #p4 from dbo.SplitToTable_Func(@sorts,',')
select * into #p5 from dbo.SplitToTable_Func(@pmtnums,',')
select * into #p6 from dbo.SplitToTable_Func(@gids,',')

--如果此处的GoodsID不为空，则说明加入的促销商品要精确到货品，所以此处的ProductName字段要存GoodsName
select pmtname=@rulename,pmtid=@PmtID,ruleid=@ruleid,rulename=@rulename,basictype=@BasicType,subtype=@SubType,
--productid=p1.value,productname=p.productname,categoryid=p.categoryid,brandid=p.brandid,brandname=p.brandname,
productid=p1.value,productname=isnull(g.GoodsName,p.productname),categoryid=p.categoryid,brandid=p.brandid,brandname=p.brandname,
goodsid=case when p6.value='' then Null else p6.value end,
marketprice=p.marketprice,memberprice=p.memberprice,pmtprice=p2.value,
pmtnumber=case when isnull(p5.value,'')='' then 0 when isnull(p5.value,'0')='0' then 0 else p5.value end,
Balance=case when isnull(p5.value,'')='' then 0 when isnull(p5.value,'0')='0' then 0 else p5.value end,
LimitedNumber=case when isnull(p3.value,'')='' then 0 when isnull(p3.value,'0')='0' then 0 else p3.value end,
IsLimited=case when isnull(p3.value,'')='' then 0 when isnull(p3.value,'0')='0' then 0 else 1 end,
addtime=@AddTime,adduser=@adduser,addusername=@addusername,status=COALESCE(@Status, (1)),SupplierID=@SupplierID,sort=p4.value,IsHomeShow=COALESCE(@IsHomeShow, (1))
into #p
--from #p1 p1,#p2 p2,#p3 p3,#p4 p4,#p5 p5,#p6 p6,product p(nolock)
--where p1.id=p2.id and p1.id=p3.id and p1.id=p4.id and p1.id=p5.id and p1.id=p6.id and p1.value=p.productid
from #p1 p1 left join #p2 p2 on p1.id=p2.id left join #p3 p3 on p1.id=p3.id left join #p4 p4 on p1.id=p4.id left join #p5 p5 on p1.id=p5.id left join #p6 p6 on p1.id=p6.id
left join product p(nolock) on p1.value=p.productid left join goods g(nolock) on p6.value=g.goodsid

insert into pmtgoods(pmtname,pmtid,ruleid,rulename,basictype,subtype,productid,productname,categoryid,brandid,brandname,goodsid,
marketprice,memberprice,pmtprice,pmtnumber,Balance,LimitedNumber,IsLimited,addtime,adduser,addusername,status,SupplierID,sort,IsHomeShow) 
select * from #p

select @errorflag=0
select @errormsg=''

RETURN SCOPE_IDENTITY()
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return 0
End Catch

end











GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtRule_LimitTime_RelatedInfo_Get]    脚本日期: 04/09/2012 18:28:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-06-04>
-- Description:	<获取促销规则相关信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PmtRule_LimitTime_RelatedInfo_Get]
@ruleid int, --规则ID
@pids varchar(8000) output,--用逗号分隔的促销商品的ID
@gids varchar(8000) output--用逗号分隔的促销货品的ID
AS
BEGIN
--获取会员组资料
SELECT membergroupid,groupname FROM MemberGroup ORDER BY MemberGroupID
--获取支付方式
select paymentid,[name] from payment where status=1

if @ruleid>0
begin
--获取促销规则基本信息
select pmtid,rulename,ruleno,begintime,endtime,GroupIDs,CanUseCoupon,IsHomeShow,BankNo,RuleAD,Remark,minvalue,maxvalue from pmtrule(nolock) where ruleid=@ruleid

--获取促销规则相关商品信息
select g.id,g.productid,g.goodsid,g.productname,g.memberprice,g.pmtprice,g.pmtnumber,g.limitednumber,g.sort,p.imgfolder,p.productimg from pmtgoods g(nolock),product p(nolock) where g.productid=p.productid and g.ruleid=@ruleid

select @pids='' 
select @pids=@pids+','+cast(productid as varchar) from pmtgoods where ruleid=@ruleid
select @pids=stuff(@pids,1,1,'')
select @gids='' 
select @gids=@gids+','+cast(goodsid as varchar) from pmtgoods where ruleid=@ruleid
select @gids=stuff(@gids,1,1,'')
end
END





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtRule_LimitTime_Update]    脚本日期: 04/09/2012 18:28:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-05-20>
-- Description:	<更新限时抢购促销规则>
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110722                              
content:                                
1.添加是否首页显示功能 

version:v1.2   
author:hakkas@qq.com                                
time:20111122                              
content:                                
1.增加参数@RuleAD用于促销广告功能 
2.修复了更改秒杀商品时，把剩余商品数量用秒杀数量覆盖的BUG。
*/
-- =============================================
CREATE PROC [dbo].[XpProc_PmtRule_LimitTime_Update]
	@RuleID int,
	@RuleName varchar(100) = NULL,
	@PmtID int = NULL,
	@RuleNo varchar(50) = NULL,
	@PmtType varchar(20)=NULL,
	@PmtTypeName varchar(50)=null,
	@BasicType varchar(50) = 'goods',
	@SubType varchar(50) = 'limittime',
	@BeginTime datetime = NULL,
	@EndTime datetime = NULL,
	@Discount decimal(18, 2) = 1,
	@LessMoney money = 0,
	@MinValue money = 0,
	@MaxValue money = 0,
	@IsAutoAdded int = 0,
	@GroupIDs varchar(50) = NULL,
	@UpdateTime datetime = NULL,
	@UpdateUser int = NULL,
	@UpdateUserName varchar(50) = NULL,
	@Status int = NULL,
	@Remark varchar(100) = NULL,
	@SupplierID int = NULL,
	@CanUseCoupon bit = NULL,
	@IsHomeShow bit = NULL,--是否首页显示
	@BankNo varchar(10),--银行编号
	@ids varchar(8000)=null,
	@pids varchar(8000)=null,
	@gids varchar(8000)=null,--秒杀用到
	@pmtprices varchar(8000)=null,
	@pmtnums varchar(8000)=null,
	@limitnums varchar(8000)=null,
	@sorts varchar(8000)=null,
	@RuleAD varchar(1000)=null,
	@errorFlag int output,
	@errorMsg varchar(200) output
AS
begin
Begin Try
select @SupplierID=COALESCE(@SupplierID, (0))
select @UpdateTime=COALESCE(@UpdateTime, getdate())

--更新活动
exec XpProc_PmtList_Update @PmtID,@RuleName,@BeginTime,@EndTime,@Remark,@Status,@UpdateTime,@UpdateUser,@UpdateUserName,@Remark,@CanUseCoupon

--更新规则
exec XpProc_PmtRule_Update @RuleID,@RuleName,@RuleNo,@PmtType,@PmtTypeName,@BasicType, @SubType,@BeginTime,@EndTime, @Discount, @LessMoney, @MinValue, @MaxValue,@IsAutoAdded, @GroupIDs,@UpdateTime,@UpdateUser,@UpdateUserName,@Status,@remark,@SupplierID,@CanUseCoupon,@IsHomeShow,@BankNo,@RuleAD

--更新促销商品
select * into #p0 from dbo.SplitToTable_Func(@ids,',')
select * into #p1 from dbo.SplitToTable_Func(@pids,',')
select * into #p2 from dbo.SplitToTable_Func(@pmtprices,',')
select * into #p3 from dbo.SplitToTable_Func(@limitnums,',')
select * into #p4 from dbo.SplitToTable_Func(@sorts,',')
select * into #p5 from dbo.SplitToTable_Func(@pmtnums,',')
select * into #p6 from dbo.SplitToTable_Func(@gids,',')

--商品的活动剩余数量
--1限时
--2秒杀(有goodsid)
--3团购(有goodsid)
--4返券
--5特价
--生成临时表#p7，用于保存实时统计出来的商品剩余数量
create table #p7(id int,value int)
--生成临时表#pb,用于保存一个活动的各个商品已购买的数量
create table #pb(ruleid int,goodsid int,qty int)
--秒杀跟团购是带goodsid的，跟限时，特价是没有goodsid的，所有要分开处理
if @pmttype=2 or @pmttype= 3
begin
insert into #pb select ruleid,goodsid,sum(quantity) as qty
from memberbookseckill(nolock)
where ruleid=@ruleid
group by ruleid,goodsid
insert into #p7 select #p6.id as id,(#p5.value-isnull(qty,0))as value
from #pb pb(nolock) right join #p6 on pb.goodsid=#p6.value and ruleid=@ruleid
right join #p5 on #p6.id=#p5.id
end
else
begin
insert into #pb select ruleid,productid,sum(quantity) as qty
from memberbookpmtgoods(nolock)
where ruleid=@ruleid
group by ruleid,productid
insert into #p7 select #p1.id as id,(#p5.value-isnull(qty,0))as value 
from #pb  pb(nolock) right join #p1 on pb.goodsid=#p1.value and ruleid=@ruleid
right join #p5 on #p1.id=#p5.id
end

--如果此处的GoodsID不为空，则说明加入的促销商品要精确到货品，所以此处的ProductName字段要存GoodsName
select id=isnull(p0.value,''),pmtname=@rulename,pmtid=@PmtID,ruleid=@ruleid,rulename=@rulename,basictype=@BasicType,subtype=@SubType,
productid=p1.value,goodsid=case when p6.value='' then Null else p6.value end,productname=isnull(g.Goodsname,p.Productname),categoryid=p.categoryid,brandid=p.brandid,brandname=p.brandname,
marketprice=p.marketprice,memberprice=p.memberprice,pmtprice=p2.value,
pmtnumber=case when isnull(p5.value,'')='' then 0 when isnull(p5.value,'0')='0' then 0 else p5.value end,
balance=case when isnull(p7.value,'')='' then 0 when isnull(p7.value,'0')='0' then 0 else p7.value end,
LimitedNumber=case when isnull(p3.value,'')='' then 0 when isnull(p3.value,'0')='0' then 0 else p3.value end,
IsLimited=case when isnull(p3.value,'')='' then 0 when isnull(p3.value,'0')='0' then 0 else 1 end,
addtime=@UpdateTime,adduser=@UpdateUser,addusername=@UpdateUserName,status=COALESCE(@Status, (1)),SupplierID=@SupplierID,sort=p4.value,IsHomeShow=COALESCE(@IsHomeShow, (1))
into #p
from #p1 p1 left join #p0 p0 on p0.id=p1.id left join #p2 p2 on p1.id=p2.id left join #p3 p3 on p1.id=p3.id left join #p4 p4 on p1.id=p4.id left join #p5 p5 on p1.id=p5.id left join #p6 p6 on p1.id=p6.id left join #p7 p7 on p1.id=p7.id
left join product p(nolock) on p1.value=p.productid left join goods g(nolock) on p6.value=g.goodsid

--删除不再存在的促销商品
delete pg from pmtgoods pg left join #p p on pg.id=p.id
where pg.ruleid=@ruleid and p.id is null

--更新促销商品
update g set pmtname=@rulename,rulename=@rulename,basictype=@basictype,subtype=@subtype,g.pmtprice=p.pmtprice,
g.pmtnumber=p.pmtnumber,g.balance=p.balance,g.LimitedNumber=p.LimitedNumber,g.IsLimited=p.IsLimited,g.updatetime=@UpdateTime,
g.updateuser=@updateuser,g.updateusername=@updateusername,g.status=p.status,g.sort=p.sort,g.IsHomeShow=p.IsHomeShow
from #p p,pmtgoods g(nolock)
where g.ruleid=p.ruleid and g.id=p.id and p.id<>''

--插入新促销商品
insert into pmtgoods(pmtname,pmtid,ruleid,rulename,basictype,subtype,productid,goodsid,productname,categoryid,brandid,
brandname,marketprice,memberprice,pmtprice,pmtnumber,balance,LimitedNumber,IsLimited,addtime,adduser,addusername,status,SupplierID,sort,IsHomeShow) 
select pmtname,pmtid,ruleid,rulename,basictype,subtype,productid,goodsid,productname,categoryid,brandid,
brandname,marketprice,memberprice,pmtprice,pmtnumber,balance,LimitedNumber,IsLimited,addtime,adduser,addusername,
status,SupplierID,sort,IsHomeShow
from #p 
where #p.id=''

select @errorflag=0
select @errormsg=''

RETURN SCOPE_IDENTITY()
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return 0
End Catch

end
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtRule_PageList_Get]    脚本日期: 04/09/2012 18:28:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-11-24>
-- Description:	<分页获取促销活动规则>
-- Debug:
--select * from pmtrule
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PmtRule_PageList_Get]
@pmttype varchar(20)=-1,--规则类型编号
@basictype varchar(20)=null,--主类型
@subtype varchar(20)=null,--次类型
@adduser int=-1,--添加人ID
@addusername varchar(20)=null,--添加人姓名
@starttime varchar(50)=null,--添加时间下限
@endtime varchar(50)=null,--添加时间上线
@supplierid int=0,--商家ID
@sort varchar(50)=null,--排序
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@totalpage int output,--总页数
@totalcount int output,--总记录数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' 1=1'

if isnull(@pmttype,-1)<>-1
select @where=@where+' and pmttype='+convert(varchar(20),@pmttype)

if isnull(@basictype,'')<>''
select @where=@where+' and basictype='+@basictype

if isnull(@subtype,'')<>''
select @where=@where+' and subtype='+@subtype

if isnull(@supplierid,-1)<>-1
select @where=@where+' and supplierid='+convert(varchar(20),@supplierid)

if isnull(@adduser,-1)<>-1
select @where=@where+' and adduser='+convert(varchar(20),@adduser)

if isnull(@addusername,'')<>''
select @where=@where+' and addusername='+@addusername

if isnull(@starttime,'')<>''
select @where=@where+' and addtime >='+@starttime

if isnull(@endtime,'')<>''
select @where=@where+' and addtime <= '+@endtime

select @sqlstr='select rowno,RuleID,RuleName,BasicType,SubType,BeginTime,EndTime,Status,Remark from (
select RuleID,RuleName,BasicType,SubType,BeginTime,EndTime,Status,Remark,Row_number() over('

if isnull(@sort,'')<>''
select @sqlstr=@sqlstr+@sort
else
select @sqlstr=@sqlstr+'order by addtime desc'

select @sqlstr=@sqlstr+ ') as rowno 
from pmtrule r(nolock) where ' + @where + ') as l where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

--print @sqlstr
--insert into log(content) values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by r.ruleid desc) as rowno from pmtrule r(nolock) where ' + @where + ') as l)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END












GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PmtRule_Update]    脚本日期: 04/09/2012 18:28:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2010-05-20>
-- Description:	<更新促销规则>
/*
引用该存储过程的存储过程：
1、XpProc_PmtRule_LimitTime_Update
2、XpProc_PmtRule_CouponIssue_Insert
*/
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110722                              
content:                                
1.添加是否首页显示功能  
  
version:v1.2   
author:hakkas@qq.com                                
time:20110726                              
content:                                
1.添加银行编号功能 1:中国银行;2:工商银行;3:建设银行;4:农业银行;5:招商银行;6:交通银行;7:光大银行  

version:v1.3   
author:hakkas@qq.com                                
time:20111122                              
content:                                
1.增加参数@RuleAD用于促销广告功能                              
*/
-- =============================================
CREATE PROC [dbo].[XpProc_PmtRule_Update]
	@RuleID int,
	@RuleName varchar(100) = NULL,
	--@PmtID int = NULL,
	@RuleNo varchar(50) = NULL,
	@PmtType varchar(20)=NULL,
	@PmtTypeName varchar(50)=NULL,
	@BasicType varchar(50) = NULL,
	@SubType varchar(50) = NULL,
	@BeginTime datetime = NULL,
	@EndTime datetime = NULL,
	@Discount decimal(18, 2) = NULL,
	@LessMoney money = NULL,
	@MinValue money = NULL,
	@MaxValue money = NULL,
	@IsAutoAdded int = NULL,
	--@Condition varchar(100) = NULL,
	@GroupIDs varchar(50) = NULL,
	--@AddTime datetime = NULL,
	--@AddUser int = NULL,
	--@AddUserName varchar(50) = NULL,
	@UpdateTime datetime = NULL,
	@UpdateUser int = NULL,
	@UpdateUserName varchar(50) = NULL,
	--@UpdateHistory varchar(800) = NULL,
	@Status int,
	--@Auditor int = NULL,
	--@AuditorName varchar(50) = NULL,
	--@AuditTime datetime = NULL,
	@Remark varchar(100) = NULL,
	@SupplierID int,
	@CanUseCoupon bit = NULL,
	@IsHomeShow bit = NULL,
	@BankNo varchar(10),--银行编号
	@RuleAD varchar(1000)=NULL --促销广告内容
AS

UPDATE	pmtrule
SET	RuleName = @RuleName,
	--PmtID = @PmtID,
	RuleNo = @RuleNo,
	PmtType=@PmtType,
	PmtTypeName=@PmtTypeName,
	BasicType = @BasicType,
	SubType = @SubType,
	BeginTime = @BeginTime,
	EndTime = @EndTime,
	Discount = @Discount,
	LessMoney = @LessMoney,
	MinValue = @MinValue,
	MaxValue = @MaxValue,
	IsAutoAdded = @IsAutoAdded,
	--Condition = @Condition,
	GroupIDs = @GroupIDs,
	UpdateTime = @UpdateTime,
	UpdateUser = @UpdateUser,
	UpdateUserName = @UpdateUserName,
	--UpdateHistory = @UpdateHistory,
	Status = COALESCE(@Status, (0)),
	--Auditor = @Auditor,
	--AuditorName = @AuditorName,
	--AuditTime = @AuditTime,
	Remark = @Remark,
	SupplierID = COALESCE(@SupplierID, (0)),
	CanUseCoupon = COALESCE(@CanUseCoupon, (0)),
	IsHomeShow = COALESCE(@IsHomeShow, (1)),
	BankNo = COALESCE(@BankNo, ('-1')),
	RuleAD = @RuleAD
WHERE 	RuleID = @RuleID





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Proc_BatchUpdateBrand]    脚本日期: 04/09/2012 18:28:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		chy
-- Create date: <2012-01-05>
-- Description:	<批量修改品牌>
-- =============================================
CREATE PROC [dbo].[XpProc_Proc_BatchUpdateBrand]
(
	@ModifiBrandID int,
	@BrandName varchar(10),
	@ProductID int=0, --商品ID

	@ProductName nvarchar(255)=null,--筛选条件/商品名称/
	@ProductNo nvarchar(50)=null,--商品编号
	@Keyword nvarchar(200)=null, --关键字
	@CategoryID int=null, --商品类别
	@BrandID int=null, --商品品牌
	@StartMemberPrice decimal=null,--开始价格区间
	@EndMemberPrice decimal=null,--结束价格区间
	@StartStorage int=null,--开始库存区间
	@EndStorage int=null,--结束库存区间
	@StartAddTime varchar(20)=null,--开始添加时间区间
	@EndAddTime varchar(20)=null,--结束添加时间区间
	@IsForSale tinyint=null,--发布状态
	@Status int=null  --审核状态
)
AS
BEGIN
	declare @sqlstr nvarchar(4000),@where nvarchar(4000)
	select @where=' 1=1'
	if @ProductName<>''
	select @where=' ProductName like '''+@ProductName+'%'''
	
	if @ProductNo>''
	select @where=@where+' and ProductNo='''+@ProductNo+''''

	if @Keyword<>''
	select @where=@where+' and Keyword like '''+@Keyword+'%'''

	if @CategoryID>0
	select @where=@where+' and CategoryID='+convert(varchar(20),@CategoryID)

	if @BrandID>0
	select @where=@where+' and BrandID='+convert(varchar(20),@BrandID)

	if @StartMemberPrice>0
	select @where=@where+' and MemberPrice between '+convert(varchar(20),@StartMemberPrice)+' and '+convert(varchar(20),@EndMemberPrice)+''
	
	if @StartStorage>0
	select @where=@where+' and Storage between '+convert(varchar(20),@StartStorage)+' and '+convert(varchar(20),@EndStorage)+''

	if @StartAddTime<>''
	select @where=@where+' and AddTime between '''+@StartAddTime+''' and '''+@EndAddTime+''''
	
	if @IsForSale<2
	select @where=@where+' and IsForSale='+convert(varchar(20),@IsForSale)

	if @Status<2
	select @where=@where+' and Status='+convert(varchar(20),@Status)
	
	
	IF @ProductID>0
	BEGIN
		UPDATE Product SET BrandID=@ModifiBrandID,BrandName=@BrandName WHERE ProductID=@ProductID
	END
	ELSE
	BEGIN
		if @where=' 1=1'
		select @where=@where+' and 1=2'
		select @sqlstr='UPDATE Product SET BrandID='+Convert(varchar(20),@ModifiBrandID)+',BrandName='''+@BrandName+''' where'+@where
		Execute(@sqlstr)
	END
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Proc_BatchUpdateIsforsale]    脚本日期: 04/09/2012 18:28:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		chy
-- Create date: <2012-01-05>
-- Description:	<批量上架、下架>
-- =============================================
CREATE PROC [dbo].[XpProc_Proc_BatchUpdateIsforsale]
(
	@type int,--1为上架，0为下架
	@ProductID int=0,

	@ProductName nvarchar(255)=null,--筛选条件/商品名称/
	@ProductNo nvarchar(50)=null,--商品ID
	@Keyword nvarchar(200)=null, --关键字
	@CategoryID int=null, --商品类别
	@BrandID int=null, --商品品牌
	@StartMemberPrice decimal=null,--开始价格区间
	@EndMemberPrice decimal=null,--结束价格区间
	@StartStorage int=null,--开始库存区间
	@EndStorage int=null,--结束库存区间
	@StartAddTime varchar(20)=null,--开始添加时间区间
	@EndAddTime varchar(20)=null,--结束添加时间区间
	@IsForSale tinyint=null,--发布状态
	@Status int=null  --审核状态
)
AS
BEGIN
	declare @sqlstr nvarchar(4000),@where nvarchar(4000)
	select @where=' 1=1'
	if @ProductName<>''
	select @where=' ProductName like '''+@ProductName+'%'''
	
	if @ProductNo>''
	select @where=@where+' and ProductNo='''+@ProductNo+''''

	if @Keyword<>''
	select @where=@where+' and Keyword like '''+@Keyword+'%'''

	if @CategoryID>0
	select @where=@where+' and CategoryID='+convert(varchar(20),@CategoryID)

	if @BrandID>0
	select @where=@where+' and BrandID='+convert(varchar(20),@BrandID)

	if @StartMemberPrice>0
	select @where=@where+' and MemberPrice between '+convert(varchar(20),@StartMemberPrice)+' and '+convert(varchar(20),@EndMemberPrice)+''
	
	if @StartStorage>0
	select @where=@where+' and Storage between '+convert(varchar(20),@StartStorage)+' and '+convert(varchar(20),@EndStorage)+''

	if @StartAddTime<>''
	select @where=@where+' and AddTime between '''+@StartAddTime+''' and '''+@EndAddTime+''''
	
	if @IsForSale<2
	select @where=@where+' and IsForSale='+convert(varchar(20),@IsForSale)

	if @Status<2
	select @where=@where+' and Status='+convert(varchar(20),@Status)

	if @type=0
	BEGIN
		if @ProductID>0
		BEGIN
			UPDATE Product SET IsForSale=0 WHERE ProductID=@ProductID
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='UPDATE Product SET IsForSale=0 WHERE'+@where
			Execute(@sqlstr)
		END
	END
	ELSE IF @type=1
	BEGIN
		IF @ProductID>0
		BEGIN
			UPDATE Product SET IsForSale=1 WHERE ProductID=@ProductID
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='UPDATE Product SET IsForSale=1 WHERE'+@where
			Execute(@sqlstr)
		END
	END
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Proc_BatchUpdateName]    脚本日期: 04/09/2012 18:28:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		chy
-- Create date: <2012-01-05>
-- Description:	<批量修改商品名称>
-- =============================================
CREATE PROC [dbo].[XpProc_Proc_BatchUpdateName]
(
	@nameType int, --1为修改全部，2为添加前缀，3为添加后缀,4为查找和替换
	@find varchar(50)=null, --查找出来的商品名称
	@replace varchar(50)=null, --替换的商品名称
	@ValueName nvarchar(255)=null, --更新的值
	@ProductName nvarchar(255), --商品名称
	@ProductID int=0, --商品ID

	@ProductNo nvarchar(50)=null,--商品ID
	@Keyword nvarchar(200)=null, --关键字
	@CategoryID int=null, --商品类别
	@BrandID int=null, --商品品牌
	@StartMemberPrice decimal=null,--开始价格区间
	@EndMemberPrice decimal=null,--结束价格区间
	@StartStorage int=null,--开始库存区间
	@EndStorage int=null,--结束库存区间
	@StartAddTime varchar(20)=null,--开始添加时间区间
	@EndAddTime varchar(20)=null,--结束添加时间区间
	@IsForSale tinyint=null,--发布状态
	@Status int=null  --审核状态
)
AS
BEGIN		
	declare @sqlstr nvarchar(4000),@where nvarchar(4000)
	select @where=' 1=1'
	if @ProductName<>''
	select @where=' ProductName like '''+@ProductName+'%'''
	
	if @ProductNo>''
	select @where=@where+' and ProductNo='''+@ProductNo+''''

	if @Keyword<>''
	select @where=@where+' and Keyword like '''+@Keyword+'%'''

	if @CategoryID>0
	select @where=@where+' and CategoryID='+convert(varchar(20),@CategoryID)

	if @BrandID>0
	select @where=@where+' and BrandID='+convert(varchar(20),@BrandID)

	if @StartMemberPrice>0
	select @where=@where+' and MemberPrice between '+convert(varchar(20),@StartMemberPrice)+' and '+convert(varchar(20),@EndMemberPrice)+''
	
	if @StartStorage>0
	select @where=@where+' and Storage between '+convert(varchar(20),@StartStorage)+' and '+convert(varchar(20),@EndStorage)+''

	if @StartAddTime<>''
	select @where=@where+' and AddTime between '''+@StartAddTime+''' and '''+@EndAddTime+''''
	
	if @IsForSale<2
	select @where=@where+' and IsForSale='+convert(varchar(20),@IsForSale)

	if @Status<2
	select @where=@where+' and Status='+convert(varchar(20),@Status)
	

	if @nameType=1
	BEGIN
		IF @ProductID>0
		BEGIN
			UPDATE Product SET ProductName=@ValueName WHERE ProductID=@ProductID
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='UPDATE Product SET ProductName='''+@ValueName+''' where'+@where
			Execute(@sqlstr)
		END
	END
	IF @nameType=2
	BEGIN
		IF @ProductID>0
		BEGIN
			UPDATE Product SET ProductName=@ValueName+ProductName WHERE ProductID=@ProductID
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='UPDATE Product SET ProductName='''+@ValueName+'''+ProductName where'+@where
			Execute(@sqlstr)
		END
	END
	IF @nameType=3
	BEGIN
		IF @ProductID>0
		BEGIN
			UPDATE Product SET ProductName=ProductName+@ValueName WHERE ProductID=@ProductID
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='UPDATE Product SET ProductName=ProductName+'''+@ValueName+''' where'+@where
			Execute(@sqlstr)
		END
	END
	IF @nameType=4
	BEGIN
		IF @ProductID>0
		BEGIN
			UPDATE Product SET ProductName=@replace WHERE ProductName=@find AND ProductID=@ProductID
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='UPDATE Product SET ProductName='''+@replace+''' where'+@where+' and ProductName='''+@find+''''
			Execute(@sqlstr)
		END
	END
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Proc_BatchUpdatePrice]    脚本日期: 04/09/2012 18:28:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		chy
-- Create date: <2012-01-05>
-- Description:	<根据选择的商品批量修改价格>
-- =============================================
CREATE PROC [dbo].[XpProc_Proc_BatchUpdatePrice]
(
	@PricType int, --1为修改全部，2为修改市场价，3为修改会员价
	@PricFlag varchar(10)=null,--用来判断修改会员价格时的运算符
	@MarketPrice decimal(18,2)=0,--市场价
	@MemberPrice decimal(18,2)=0,--会员价
		

	@ProductID int=0, --商品ID
	@ProductName nvarchar(255)=null, --商品名称
	@ProductNo nvarchar(50)=null,--商品
	@Keyword nvarchar(200)=null, --关键字

	@CategoryID int=null, --商品类别
	@BrandID int=null, --商品品牌
	@StartMemberPrice decimal=null,--开始价格区间
	@EndMemberPrice decimal=null,--结束价格区间
	@StartStorage int=null,--开始库存区间
	@EndStorage int=null,--结束库存区间
	@StartAddTime varchar(20)=null,--开始添加时间区间
	@EndAddTime varchar(20)=null,--结束添加时间区间
	@IsForSale tinyint=null,--发布状态
	@Status int=null  --审核状态
)
AS
BEGIN
	declare @sqlstr nvarchar(4000),@where nvarchar(4000)
	select @where=' 1=1'
	if @ProductName<>''
	select @where=' ProductName like '''+@ProductName+'%'''
	
	if @ProductNo>''
	select @where=@where+' and ProductNo='''+@ProductNo+''''

	if @Keyword<>''
	select @where=@where+' and Keyword like '''+@Keyword+'%'''

	if @CategoryID>0
	select @where=@where+' and CategoryID='+convert(varchar(20),@CategoryID)

	if @BrandID>0
	select @where=@where+' and BrandID='+convert(varchar(20),@BrandID)

	if @StartMemberPrice>0
	select @where=@where+' and MemberPrice between '+convert(varchar(20),@StartMemberPrice)+' and '+convert(varchar(20),@EndMemberPrice)+''
	
	if @StartStorage>0
	select @where=@where+' and Storage between '+convert(varchar(20),@StartStorage)+' and '+convert(varchar(20),@EndStorage)+''

	if @StartAddTime<>''
	select @where=@where+' and AddTime between '''+@StartAddTime+''' and '''+@EndAddTime+''''
	
	if @IsForSale<2
	select @where=@where+' and IsForSale='+convert(varchar(20),@IsForSale)

	if @Status<2
	select @where=@where+' and Status='+convert(varchar(20),@Status)

	
	if @PricType=1
	BEGIN
		IF @ProductID>0
		BEGIN
			update Product set MarketPrice=@MarketPrice,MemberPrice=@MemberPrice where ProductID=@ProductID
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='update Product set MarketPrice='+convert(varchar(100),@MarketPrice)+',MemberPrice='+convert(varchar(100),@MemberPrice)+' where'+@where
			Execute(@sqlstr)
		END
	END
	IF @PricType=2
	BEGIN
		IF @ProductID>0
		BEGIN
			IF @PricFlag='1'
			BEGIN
				update Product set MarketPrice=MarketPrice+@MarketPrice where ProductID=@ProductID
			END
			ELSE IF @PricFlag='2'
			BEGIN
				update Product set MarketPrice=MarketPrice-@MarketPrice where ProductID=@ProductID
			END
			ELSE IF @PricFlag='3'
			BEGIN
				update Product set MarketPrice=MarketPrice*@MarketPrice where ProductID=@ProductID	
			END
			ELSE IF @PricFlag='4'
			BEGIN
				update Product set MarketPrice=MarketPrice/@MarketPrice where ProductID=@ProductID	
			END
		END
		ELSE
		BEGIN
			IF @PricFlag='1'
			BEGIN
				if @where=' 1=1'
				select @where=@where+' and 1=2'
				select @sqlstr='update Product set MarketPrice=MarketPrice+'+convert(varchar(100),@MarketPrice)+' where'+@where
				Execute(@sqlstr)
			END
			ELSE IF @PricFlag='2'
			BEGIN
				if @where=' 1=1'
				select @where=@where+' and 1=2'
				select @sqlstr='update Product set MarketPrice=MarketPrice-'+convert(varchar(100),@MarketPrice)+' where'+@where
				print(@sqlstr)
				Execute(@sqlstr)
			END
			ELSE IF @PricFlag='3'
			BEGIN
				if @where=' 1=1'
				select @where=@where+' and 1=2'
				select @sqlstr='update Product set MarketPrice=MarketPrice*'+convert(varchar(100),@MarketPrice)+' where'+@where
				print(@sqlstr)
				Execute(@sqlstr)
			END
			ELSE IF @PricFlag='4'
			BEGIN
				if @where=' 1=1'
				select @where=@where+' and 1=2'
				select @sqlstr='update Product set MarketPrice=MarketPrice/'+convert(varchar(100),@MarketPrice)+' where'+@where
				print(@sqlstr)
				Execute(@sqlstr)
			END
		END
	END
	IF @PricType=3
	BEGIN
		IF @ProductID>0
		BEGIN
			IF @PricFlag='1'
			BEGIN
				update Product set MemberPrice=MemberPrice+@MemberPrice where ProductID=@ProductID
			END
			ELSE IF @PricFlag='2'
			BEGIN			
				update Product set MemberPrice=MemberPrice-@MemberPrice where ProductID=@ProductID		
			END
			ELSE IF @PricFlag='3'
			BEGIN
				update Product set MemberPrice=MemberPrice*@MemberPrice where ProductID=@ProductID	
			END
			ELSE IF @PricFlag='4'
			BEGIN
				update Product set MemberPrice=MemberPrice/@MemberPrice where ProductID=@ProductID	
			END
		END
		ELSE
		BEGIN
			IF @PricFlag='1'
			BEGIN
				if @where=' 1=1'
				select @where=@where+' and 1=2'
				select @sqlstr='update Product set MemberPrice=MemberPrice+'+convert(varchar(100),@MemberPrice)+' where'+@where
				print(@sqlstr)
				Execute(@sqlstr)
			END
			ELSE IF @PricFlag='2'
			BEGIN			
				if @where=' 1=1'
				select @where=@where+' and 1=2'
				select @sqlstr='update Product set MemberPrice=MemberPrice-'+convert(varchar(100),@MemberPrice)+' where'+@where
				print(@sqlstr)
				Execute(@sqlstr)
			END
			ELSE IF @PricFlag='3'
			BEGIN
				if @where=' 1=1'
				select @where=@where+' and 1=2'
				select @sqlstr='update Product set MemberPrice=MemberPrice*'+convert(varchar(100),@MemberPrice)+' where'+@where
				print(@sqlstr)
				Execute(@sqlstr)
			END
			ELSE IF @PricFlag='4'
			BEGIN
				if @where=' 1=1'
				select @where=@where+' and 1=2'
				select @sqlstr='update Product set MemberPrice=MemberPrice/'+convert(varchar(100),@MemberPrice)+' where'+@where
				print(@sqlstr)
				Execute(@sqlstr)
			END
		END
	END
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Proc_BatchUpdateShortDesc]    脚本日期: 04/09/2012 18:28:48 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		chy
-- Create date: <2012-01-05>
-- Description:	<批量修改商品简介>
-- =============================================
CREATE PROC [dbo].[XpProc_Proc_BatchUpdateShortDesc]
(
	@ShortDescType int, --1为修改全部，2为添加前缀，3为添加后缀,4为查找和替换
	@find varchar(50)=null, --查找出来的商品简介
	@replace varchar(50)=null, --替换的商品简介
	@ShortDesc nvarchar(255), --商品简介
	@ProductID int=0, --商品ID
	
	@ProductName nvarchar(255), --商品名称
	@ProductNo nvarchar(50)=null,--商品关键字
	@Keyword nvarchar(200)=null, --关键字
	@CategoryID int=null, --商品类别
	@BrandID int=null, --商品品牌
	@StartMemberPrice decimal=null,--开始价格区间
	@EndMemberPrice decimal=null,--结束价格区间
	@StartStorage int=null,--开始库存区间
	@EndStorage int=null,--结束库存区间
	@StartAddTime varchar(20)=null,--开始添加时间区间
	@EndAddTime varchar(20)=null,--结束添加时间区间
	@IsForSale tinyint=null,--发布状态
	@Status int=null  --审核状态
)
AS
BEGIN
	declare @sqlstr nvarchar(4000),@where nvarchar(4000)
	select @where=' 1=1'
	if @ProductName<>''
	select @where=' ProductName like '''+@ProductName+'%'''
	
	if @ProductNo>''
	select @where=@where+' and ProductNo='''+@ProductNo+''''

	if @Keyword<>''
	select @where=@where+' and Keyword like '''+@Keyword+'%'''

	if @CategoryID>0
	select @where=@where+' and CategoryID='+convert(varchar(20),@CategoryID)

	if @BrandID>0
	select @where=@where+' and BrandID='+convert(varchar(20),@BrandID)

	if @StartMemberPrice>0
	select @where=@where+' and MemberPrice between '+convert(varchar(20),@StartMemberPrice)+' and '+convert(varchar(20),@EndMemberPrice)+''
	
	if @StartStorage>0
	select @where=@where+' and Storage between '+convert(varchar(20),@StartStorage)+' and '+convert(varchar(20),@EndStorage)+''

	if @StartAddTime<>''
	select @where=@where+' and AddTime between '''+@StartAddTime+''' and '''+@EndAddTime+''''
	
	if @IsForSale<2
	select @where=@where+' and IsForSale='+convert(varchar(20),@IsForSale)

	if @Status<2
	select @where=@where+' and Status='+convert(varchar(20),@Status)

	
	if @ShortDescType=1
	BEGIN
		IF @ProductID>0
		BEGIN
			UPDATE Product SET ShortDesc=@ShortDesc WHERE ProductID=@ProductID
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='UPDATE Product SET ShortDesc='''+@ShortDesc+''' where'+@where
			Execute(@sqlstr)
		END
	END
	IF @ShortDescType=2
	BEGIN
		IF @ProductID>0
		BEGIN
			UPDATE Product SET ShortDesc=@ShortDesc+ShortDesc WHERE ProductID=@ProductID
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='UPDATE Product SET ShortDesc='''+@ShortDesc+'''+ShortDesc where'+@where
			Execute(@sqlstr)
		END		
	END
	IF @ShortDescType=3
	BEGIN
		IF @ProductID>0
		BEGIN
			UPDATE Product SET ShortDesc=ShortDesc+@ShortDesc WHERE ProductID=@ProductID
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='UPDATE Product SET ShortDesc=ShortDesc+'''+@ShortDesc+''' where'+@where
			Execute(@sqlstr)
		END
	END
	IF @ShortDescType=4
	BEGIN
		IF @ProductID>0
		BEGIN
			UPDATE Product SET ShortDesc=@replace WHERE ShortDesc=@find AND ProductID=@ProductID
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='UPDATE Product SET ShortDesc='''+@replace+''' where'+@where+' and ShortDesc='''+@find+''''
			Execute(@sqlstr)
		END		
	END
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Proc_BatchUpdateWeight]    脚本日期: 04/09/2012 18:28:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		chy
-- Create date: <2012-01-05>
-- Description:	<批量修改重量>
-- =============================================
CREATE PROC [dbo].[XpProc_Proc_BatchUpdateWeight]
(
	@weightType int, --2为按条件修改，1为修改全部
	@WeightFlag varchar(10)=null,--用来判断修改重量时的运算符
	@Weight decimal(18,2),--重量
	@ProductID int=0, --商品ID

	@ProductName nvarchar(255), --商品名称
	@ProductNo nvarchar(50)=null,--商品ID
	@Keyword nvarchar(200)=null, --关键字
	@CategoryID int=null, --商品类别
	@BrandID int=null, --商品品牌
	@StartMemberPrice decimal=null,--开始价格区间
	@EndMemberPrice decimal=null,--结束价格区间
	@StartStorage int=null,--开始库存区间
	@EndStorage int=null,--结束库存区间
	@StartAddTime varchar(20)=null,--开始添加时间区间
	@EndAddTime varchar(20)=null,--结束添加时间区间
	@IsForSale tinyint=null,--发布状态
	@Status int=null  --审核状态	
)
AS
BEGIN
	declare @sqlstr nvarchar(4000),@where nvarchar(4000)
	select @where=' 1=1'
	if @ProductName<>''
	select @where=' ProductName like '''+@ProductName+'%'''
	
	if @ProductNo>''
	select @where=@where+' and ProductNo='''+@ProductNo+''''

	if @Keyword<>''
	select @where=@where+' and Keyword like '''+@Keyword+'%'''

	if @CategoryID>0
	select @where=@where+' and CategoryID='+convert(varchar(20),@CategoryID)

	if @BrandID>0
	select @where=@where+' and BrandID='+convert(varchar(20),@BrandID)

	if @StartMemberPrice>0
	select @where=@where+' and MemberPrice between '+convert(varchar(20),@StartMemberPrice)+' and '+convert(varchar(20),@EndMemberPrice)+''
	
	if @StartStorage>0
	select @where=@where+' and Storage between '+convert(varchar(20),@StartStorage)+' and '+convert(varchar(20),@EndStorage)+''

	if @StartAddTime<>''
	select @where=@where+' and AddTime between '''+@StartAddTime+''' and '''+@EndAddTime+''''
	
	if @IsForSale<2
	select @where=@where+' and IsForSale='+convert(varchar(20),@IsForSale)

	if @Status<2
	select @where=@where+' and Status='+convert(varchar(20),@Status)


	IF @weightType=1
	BEGIN
		IF @ProductID>0
		BEGIN
			update Product set Weight=@Weight where ProductID=@ProductID 
		END
		ELSE
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='update Product set Weight='+convert(varchar(100),@Weight)+' where'+@where
			Execute(@sqlstr)
		END
	END
	if @weightType=2
	BEGIN
		IF @ProductID>0
		BEGIN
			IF @WeightFlag='1'
			BEGIN
				update Product set Weight=Weight+@Weight where ProductID=@ProductID
			END
			ELSE IF @WeightFlag='2'
			BEGIN
				update Product set Weight=Weight-@Weight where ProductID=@ProductID
			END
			ELSE IF @WeightFlag='3'
			BEGIN
				update Product set Weight=Weight*@Weight where ProductID=@ProductID
			END
			ELSE IF @WeightFlag='4'
			BEGIN
				update Product set Weight=Weight/@Weight where ProductID=@ProductID
			END
		END
		ELSE
		BEGIN
			IF @WeightFlag='1'
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='update Product set Weight=Weight+'+convert(varchar(100),@Weight)+' where'+@where
			Execute(@sqlstr)
		END
		ELSE IF @WeightFlag='2'
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='update Product set Weight=Weight-'+convert(varchar(100),@Weight)+' where'+@where
			Execute(@sqlstr)
		END
		ELSE IF @WeightFlag='3'
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='update Product set Weight=Weight*'+convert(varchar(100),@Weight)+' where'+@where
			Execute(@sqlstr)
		END
		ELSE IF @WeightFlag='4'
		BEGIN
			if @where=' 1=1'
			select @where=@where+' and 1=2'
			select @sqlstr='update Product set Weight=Weight/'+convert(varchar(100),@Weight)+' where'+@where
			Execute(@sqlstr)
		END
		END
	END
	
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Product_Delete]    脚本日期: 04/09/2012 18:28:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2010-06-23>
-- Description:	<删除商品>
-- =============================================

CREATE PROC [dbo].[XpProc_Product_Delete](
	@pdtids varchar(8000),--要删除的商品ID集合
	@memberid int=null,
	@membername nvarchar(100)=null, 
	@ip nvarchar(40)=null,
	@flag int ,--0逻辑删除 1物理删除,2从回收站还原商品
	@errorFlag int =1 output
)
AS
begin
	begin try
	begin tran
	select *  into #temp from dbo.SplitToTable_Func(@pdtids,',')
	--逻辑删除
	if(@flag=0)
	begin
	--写系统日志
	INSERT INTO EventLog (MemberID,MemberName,RootCatID,SubCatID,Description,IP,AddTime)
	select @memberid,@membername, 4,46,'删除商品到回收站:'+productname, @ip ,getDate() from #temp,product where product.productid=#temp.[value]
	--批量更改商品的isdel,isforsale,status的状态
	update product set isdel=1,isforsale=0,status=0,updatetime=getDate() from #temp where product.productid=#temp.[value]
	end
	--物理删除
	else if(@flag=1)
	begin
	--写系统日志
	INSERT INTO EventLog (MemberID,MemberName,RootCatID,SubCatID,Description,IP,AddTime)
	select @memberid,@membername, 4,46,'彻底删除商品:'+productname, @ip ,getDate() from #temp,product where product.productid=#temp.[value]
	--删除配件
--	delete from fitting where productid in(select [value] from #temp)
--	delete from fitting where exists(select *from #temp where fitting.productid=#temp.[value])
	delete fitting from fitting,#temp where fitting.productid=#temp.[value]
	--删除相关商品(rltpdts)
	delete rltpdts from rltpdts,#temp where rltpdts.productid=#temp.[value]
	--删除促销商品记录
	delete pmtgoods from pmtgoods ,#temp where pmtgoods.productid=#temp.[value]
	--删除促销礼品记录
	delete pmtgifts from pmtgifts,#temp where pmtgifts.productid=#temp.[value]
    --删除商品状态
	delete pdttag from pdttag ,#temp where pdttag.productid=#temp.[value]
	--删除商品评论及评论的回复
	select productreviewid into #productreviewid from productreview ,#temp where productreview.productid=#temp.[value]
	delete reviewreply from reviewreply,#productreviewid where reviewreply.productreviewid=#productreviewid.productreviewid
	delete productreview from productreview,#productreviewid where productreview.productreviewid=#productreviewid.productreviewid
	--删除商品购买咨询
	delete productask from productask,#temp where productask.productid=#temp.[value]
	--删除图片记录
	delete pdtimg from pdtimg,#temp where pdtimg.pid=#temp.[value]
	--删除货品信息
	delete goods from goods,#temp where goods.productid=#temp.[value]
    --删除商品信息
	delete product from product,#temp where product.productid=#temp.[value]
	--删除赠品信息
	delete present from present,#temp where present.productid= #temp.[value]
	end
	--从回收站还原商品
	else if(@flag=2)
	begin
	update product set isdel=0 ,status=0,isforsale=0,updatetime=getDate() from #temp where Product.productid=#temp.[value]	
	--写系统日志
	INSERT INTO EventLog (MemberID,MemberName,RootCatID,SubCatID,Description,IP,AddTime)
	select @memberid,@membername, 4,48,'从回收站还原商品:'+productname, @ip ,getDate() from #temp,product where product.productid=#temp.[value]
	end
	set @errorflag=0
	commit tran
	end try
	begin catch
	rollback tran
	select @errorFlag=1
	end catch
end





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ProductList_Select]    脚本日期: 04/09/2012 18:28:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-09>
-- Description:	<用于商家后台，商品的查询与编辑>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ProductList_Select] (
@pageIndex int,
@pageSize int,
@strWhere varchar(4000),--搜索条件
--@ordersort varchar(20),
@sid int =-1 , --商家ID
@totalCount int output
)
AS
Begin
declare @sql1 varchar(8000)
declare @sql2 nvarchar(4000)
declare @befrows varchar(10)
set @befrows=@pageSize*(@pageindex-1)
--table[0] 一个商家产品的一二级分类，绑定到搜索栏里去
select * into #ssc from subcategory(nolock) where sid=@sid
select s1.sid,s1.depth,s1.cid as cid,case when s1.depth=1 then s1.cname else '|-'+s1.cname  end as cname ,s1.logo as logo,s1.stype,s1.childs as childs,isnull(s2.sort,s1.sort) as ssort,left(s1.cid,2)
as cno from #ssc s1 left join #ssc s2 on s1.parentid=s2.cid order by ssort,cno,s1.depth,s1.sort,cid

--table[1]分页的商品
--select  top 0 productid, productno,thumbnailimg,productname,CategoryNo,BrandName,memberprice,dbo.f_getStorage(productid) as stroage,cid,cname,product.status,isforsale into #temp1 from product,subcategory where product.subcategoryid=subcategory.cid and sid=@sid
--insert #temp1 select productid, productno,thumbnailimg,productname,CategoryNo,BrandName,memberprice,dbo.f_getStorage(productid) as stroage,cid,cname,product.status,isforsale from product,subcategory where product.subcategoryid=subcategory.cid and sid=@sid

select productid, productno,thumbnailimg,productname,BrandName,memberprice,storage,cid,cname,p.status,isforsale,imgfolder ,IsDel into #temp1 
from product p(nolock)
left join subcategory s(nolock)
on p.subcategoryid=s.cid and s.sid=@sid
where p.supplierid=@sid and isDel=0
set @sql1='select top '+cast(@pageSize as nvarchar(50))+'* from  #temp1  where '+@strWhere+' and  productid not in (select top '+cast(@befrows as nvarchar(50))+' productid from  #temp1  where '+@strWhere+'order by productid desc )order by productid desc'
exec(@sql1)
--符合条件的总商品数量
set @sql2=N'select @totalCount=count(*) from #temp1 where '+@strWhere
exec sp_executesql @sql2,N'@totalCount int out',@totalCount out
End






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ProductNum_Update]    脚本日期: 04/09/2012 18:28:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-12-31>
-- Description:	<更新商品库存，要更新product,goods表中的库存数量及更新Product表中的Skumap>
-- Debug:
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ProductNum_Update]
	@productids varchar(8000)=null,
	@goodsids varchar(8000)=null,
	@quantitys varchar(8000),--更新的库存数量
	@flag bit,--0是减库存 1是加库存
	@errorflag int=null output,
	@errormsg varchar(200)=null output
AS
begin
set nocount on
select @errorflag=1
select @errormsg=''
Begin try
begin tran

select a.value as 'goodsID',b.value as 'flag',c.value as 'quantity' into #t1
from
(select *from dbo.SplitToTable_Func(@goodsids,','))a,
(select *from dbo.SplitToTable_Func(@flag,','))b,
(select *from dbo.SplitToTable_Func(@quantitys,','))c
where a.id=b.id and b.id=c.id

--更新货品的库存
update goods set storage= case @flag when 1 then storage+quantity when 0 then storage-quantity end
from goods g,#t1 t
where g.goodsid=t.goodsid
--更新商品的库存
--要更新的商品表的的Productid
select distinct(productid) into #t2 from goods g(nolock),#t1 where goods.goodsid=#t1.goodsid
--重新统计product表中的库存数量，因为相关的商品goods表中的库存已有变化
UPDATE product
SET product.storage= a.storage
from 
(SELECT g.productid,sum(isnull(storage,0))storage 
FROM goods g(nolock),#t2
where goods.productid=#t2.productid
GROUP BY goods.productid )a
WHERE product.Productid = a.Productid

--更新Product表中的Skumap
declare @productid int,@skumap varchar(8000),@propid varchar(50),@goodsid int,@goodsprice decimal(18,2),@goodsstock int,@goodsno varchar(50)
declare products_items_cursor cursor for
select productid from #t2
open products_items_cursor
fetch next from products_items_cursor into
@productid
while @@fetch_status=0
begin
	--构造SkuMap并更新到商品表
	declare goods_items_cursor cursor for                                                    
	select goodsid,goodsno,memberprice,storage,isnull(props,'0:0;0:0')
	from goods
	where productid=@productid
	order by goodsid asc
	select @skumap='{'
	--遍历游标
	open goods_items_cursor                                                    
	fetch next from goods_items_cursor into 
	@goodsid,@goodsno,@goodsprice,@goodsstock,@propid
	while @@fetch_status = 0                        
	begin 
	select @skumap=@skumap+'"'+@propid+'":{"skuId":"'+cast(@goodsid as varchar(50))+'","price":"'+cast(@goodsprice as varchar(50))+'","stock":"'+cast(@goodsstock as varchar(50))+'","code":"'+@goodsno+'"},'
	fetch next from goods_items_cursor into 
	@goodsid,@goodsno,@goodsprice,@goodsstock,@propid
	end
	set @skumap=STUFF(@skumap,len(@skumap),1,'}')
	update product set skumap=@skumap where productid=@productid
	--遍历结束
	close goods_items_cursor                                                    
	deallocate goods_items_cursor
	fetch next from products_items_cursor into @productid
end                                           
close products_items_cursor   
deallocate products_items_cursor
select @errorflag=0
select @errormsg='更新成功'

commit tran

End Try

Begin Catch
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
declare @err varchar(1000),@severity int 
set @err=ERROR_MESSAGE();
set @severity=ERROR_SEVERITY();
RAISERROR(@err,@severity,1);
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ProductReview_Check]    脚本日期: 04/09/2012 18:28:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-03>
-- Description:	<验证会员是否可以对某个商家的商品进行评价>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ProductReview_Check] (
@orderID int,--订单ID
@orderProductID int,--OrderProduct 表中 一个订单中对应的一个OrderProductID
@productID int , --产品ID
@memberID int,--评论者ID
@errorFlag int=0 out,     --是否错误标识，0 会员可以评价，1时没有购买或已经评价过这个商品 ，2不是会员的订单 3 订单不包括这个商品
@errorMsg nvarchar(100) out   --错误信息提示 
)
AS
--begin
--if @orderID= 0  --在商品详细页进行商品评价
--begin
--	select top 1 @orderID=o.orderid from orders o ,orderproduct op where o.status=7 and o.memberid=@memberID and o.orderid=op.orderid and productid=@productID 
--	and o.orderid not in(select orderid from productreview where orderid=o.orderid and productid=@productID)order by ordertime
--	if(@orderid=0)
--	begin
--		select @errorFlag=1
--		select @errorMsg='您还未购买过该商品或已经评价过该商品，不能评价！'
--	end
--	else
--		select @errorFlag=0,@errorMsg=''
--end
--else --在订单明细里面进行商品评价,带有订单ID
--begin
----	if not exists(select orderid from orders where orderid=@orderid and status=7 or status=12)
----	begin
----		select @errorFlag=1
----		select @errorMsg='这个订单没有签收或已取消，不能评价! '
----		return
----	end
--	--这个订单不属于这个会员的
--	if not exists(select orderid from orders where orderid=@orderid and memberid=@memberid)
--	begin
--		select @errorFlag=1
--		select @errorMsg='不是你下的订单，不能评价! '
--		return
--	end
--	--这个订单不包含这个商品
--	if not exists(select productid from orderproduct where orderid=@orderid and productid=@productid)
--	begin
--		select @errorFlag=1
--		select @errorMsg='订单没有这个商品! '
--		return
--	end
--	if not exists(select productreviewid from productreview where orderid = @orderID and productid = @productID) --该订单商品没有评价记录
--	begin	
--	select @errorFlag=0
--	select @errorMsg=''
--	end
--	else
--	begin
--		select @errorFlag=1
--		select @errorMsg='您已经评价过该商品！'
--	end
--end
begin
if @orderID= 0  --在商品详细页进行商品评价
begin
	if not exists (select commentstatus from orderproduct(nolock) where productid=@productID and memberid=@memberid and commentstatus=1)
	begin
		select @errorFlag=1
		select @errorMsg='你还不能评价这个商品！'
	end
	else
	begin
		select @errorFlag=0,@errorMsg=''
	end
end
else --对指定订单的商品进行评价
begin
	if not exists(select orderid from orders(nolock) where orderid=@orderid and memberid=@memberid)
	begin
		select @errorFlag=1
		select @errorMsg='这个不是你下的订单! '
		return
	end
	if not exists(select productid from orderproduct(nolock) where orderid=@orderid and productid=@productid)
	begin
		select @errorFlag=1
		select @errorMsg='这个订单没有这个商品! '
		return
	end
	declare @commentstatus int
--	select @commentstatus=commentstatus from orderproduct(nolock) op,orders(nolock) p 
--where op.orderid=p.orderid and op.productid=@productID and  op.memberid=@memberid and op.orderid=@orderid and orderproductid=@orderproductid
	select @commentstatus=commentstatus from orderproduct(nolock) op 
	where op.productid=@productID and  op.memberid=@memberid and op.orderid=@orderid and orderproductid=@orderproductid
	if(@commentstatus=0 or @commentstatus is null)
	begin	
	select @errorFlag=1
	select @errorMsg='还不能评价这个商品！'
	end
	else if(@commentstatus=2)
	begin
		select @errorFlag=1
		select @errorMsg='您已经评价过这个商品！'
	end
	else if(@commentstatus=1)
	begin
		select @errorFlag=0
		select @errorMsg=''
	end
--	else if(@commentstatus is null)
--	begin
--		select @errorFlag=1
--		select @errorMsg='未知错误'
--	end
end
end






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ProductReview_Delete]    脚本日期: 04/09/2012 18:28:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-04>
-- Description:	<后台管理员删除对商品的评价>
--20111117
--增加后台批量删除商品评论的功能
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ProductReview_Delete] (
@prids varchar(300),--ProductReview表中的，ProductReviewID
@auditor int, --审核人ID 
@auditorname varchar(20), --审核人账号 
@ip varchar(20),--审核人IP 
@errorFlag int out     --是否错误标识，<>0 时，显示错误信息
--@errorMessage nvarchar(100)='' out   --错误信息提示 
)
AS
Begin
declare @sscore int --评分
declare @score int --赠送积分
declare @orlstatus int --更新前的状态 
declare @memberid int --评价会员ID
declare @productid int --评价的商品ID 

select @errorFlag=1
begin try
begin tran
	select id,value as prid into #t from SplitToTable_Func(@prids,',')
	declare @prid int
	declare cursor_prid cursor for
	select prid from #t order by prid 
	open cursor_prid
	fetch next from cursor_prid into @prid
	while @@fetch_status=0
	begin

		select @memberid=memberid,@orlstatus=status,@sscore=score,@score=memberscore,@productid=productid from productreview  where productreviewid = @prid
		--评论有回复时要删除回复
		delete from ReviewReply Where ProductReviewID =@prid
		--删除的评论，有三种情况：未审核，已审核未通过，已审核通过
		--如果删除的评论是已审核通过，还要减去发表这个评论的会员获得的积分，及更新Product表中的Review,Pj等字段的值
		if(@orlstatus=2)--已审核的评价
		begin 
			if(@score<>0)--评价有赠送积分
			begin 
			print('删除已审批的评价时要减去赠送的积分')
--				update member set score=score-@score where memberid=@memberid 会员表的积分计算放在存储过程XpProc_ScoreLog_Insert中计算
				exec XpProc_ScoreLog_Insert @memberid,null,@score,-1,1,0,null,'删除商品评论',@prid,'删除商品评论减去积分','删除商品评论减去积分',@ip,null,null,@auditor,@auditorname
			end
			print('减评论数')
			if(@sscore=1) 
			begin 
				update product set reviews=(case when (reviews-5>0) then (reviews-1) else 0 end),pj5=(case when (pj5-1>0) then (pj5-1) else 0 end) where productid=@productid  
			end 
			else if(@sscore=2) 
			begin
				update product set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end),pj4=(case when (pj4-1>0) then (pj4-1) else 0 end) where productid=@productid 
			end
			else if(@sscore=3) 
			begin
				update product set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end),pj3=(case when (pj3-1>0) then (pj3-1) else 0 end) where productid=@productid 
			end 
			else if(@sscore=4) 
			begin 
				update product set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end),pj2=(case when (pj2-1>0) then (pj2-1) else 0 end) where productid=@productid 
			end 
			else 
			begin 
				update product set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end),pj1=(case when (pj1-1>0) then (pj1-1) else 0 end) where productid=@productid  
			end
		end
		print('删除评价') 
		delete from ProductReview where ProductReviewID in (@prid)
		print('更新商品平均评分') 
		update product set pingfen=(select cast(round(avg(score*1.0),0) as int) from productreview where status=2 and productid =@productid group by productid)  where productid = @productid 
	fetch next from cursor_prid into @prid
	end
	close cursor_prid
	deallocate cursor_prid
select @errorFlag=0
commit
end try
begin catch
rollback
select @errorFlag=1
end catch
End
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ProductReview_Insert]    脚本日期: 04/09/2012 18:28:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-03>
-- Description:	<会员对购买过的某个商家的商品进行评价>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ProductReview_Insert] (
@orderID int,--订单ID
@orderproductid int,--OrderProductID
@productID int , --产品ID
@memberID int,--评论者ID
@title varchar(510), --评价标题
@body ntext,--评价内容
@score int,--评分
@ip varchar(40),--评价人IP
@memberName varchar(100), --评论人账号
@memberScore int,--会员积分 
@reviewType int, --评论类型 1，商品评论，2拍卖商品评论，3团购商品评论，4礼品评论
@isToMessage tinyint, --是否发送至小信使
@errorFlag int =0 out,     --是否错误标识，<>0 时，显示错误信息@errorMessage nvarchar(100)='' out   --错误信息提示 
@errorMessage nvarchar(100)='' out
)
AS
--Begin
--	declare @orderNo varchar(100)--订单编号
--	declare @orderTime datetime--下订时间
--	declare @supplierID int--商家ID
--	declare @maxID int 
--
--	if (@orderid = 0)  --在商品详细页进行商品评价
--	begin
--		select top 1 @orderID=o.orderid,@orderNo=o.orderno,@orderTime=o.ordertime,@supplierID=o.supplierid from orders o ,orderproduct op where o.status=7 and o.memberid=@memberID and o.orderid=op.orderid and productid=@productID 
--		and o.orderid not in(select orderid from productreview where orderid=o.orderid and productid=@productID)
--		order by ordertime
--		if (@orderid=0) --没有包含该商品的订单或已经评价过该商品
--			select @errorFlag=1,@errorMessage='您还未购买过该商品或已经评价过该商品，不能评价！'
--		else
--		begin
--			select @maxID=max(ProductReviewID)+1 from ProductReview(nolock)
--			insert ProductReview(ProductReviewID,ProductID,MemberID,Title,Body,Score,AddTime,IP,YesNum,NotNum,Status,MemberName,MemberScore,ReviewType,IsToMessage,OrderID,OrderNo,OrderTime,SupplierID,IsReply)values(@maxID,@productID,@memberID,@title,@body,@score,getDate(),@ip,0,0,0,@membername,@memberScore,@reviewtype,@istomessage,@orderid,@orderno,@ordertime,@supplierID,0)
--			select @errorFlag=0,@errorMessage=''
--		end
--	end
--	else --在订单明细里面进行商品评价
--	begin
----		declare @tempMemberID int
----		select @tempMemberID=memberid from orders where orderid=@orderid
----		if(@tempMemberID<>@memberID)
--		--这个订单不属于这个会员的
--		if not exists(select orderid from orders where orderid=@orderid and memberid=@memberid)
--		begin
--			select @errorFlag=1,@errorMessage='不是你下的订单的商品，不能评价! '
--			return
--		end
--		--这个订单不包含这个商品
--		if not exists(select productid from orderproduct where orderid=@orderid and productid=@productid)
--		begin
--			select @errorFlag=1,@errorMessage='订单没有这个商品! '
--			return
--		end
--		if not exists(select productreviewid from productreview where orderid = @orderid and productid = @productid) --该订单商品没有评价记录
--		begin
--			select top 1 @orderNo=orderno,@orderTime=ordertime,@supplierID=supplierid from orders where orders.orderid=@orderid 
--			select @maxID=max(ProductReviewID)+1 from ProductReview(nolock)
--			insert ProductReview(ProductReviewID,ProductID,MemberID,Title,Body,Score,AddTime,IP,YesNum,NotNum,Status,MemberName,MemberScore,ReviewType,IsToMessage,OrderID,OrderNo,OrderTime,SupplierID,IsReply)values(@maxID,@productID,@memberID,@title,@body,@score,getDate(),@ip,0,0,0,@membername,@memberScore,@reviewtype,@istomessage,@orderid,@orderno,@ordertime,@supplierID,0)
--			select @errorFlag=0,@errorMessage=''
--		end
--		else
--		begin
--			select @errorFlag=1,@errorMessage='您已经评价过该商品！'
--		end
--	end
--End
begin
	declare @orderNo varchar(100)--订单编号
	declare @orderTime datetime--下订时间
	declare @supplierID int--商家ID
--	declare @orderProductID int--OrderProductID
	if (@orderid = 0)  --在商品详细页进行商品评价
	begin
		--检查是否可以评价
		exec XpProc_ProductReview_Check @orderID,@orderproductid,@productid,@memberID ,@errorFlag out,@errorMessage out
		if(@errorFlag=1)
		begin
			return
		end
		else
		begin
			select top 1 @orderProductID=OrderProductID,@orderID=o.orderid,@orderNo=o.orderno,@orderTime=o.ordertime,@supplierID=o.supplierid from orders o ,orderproduct op where o.orderid=op.orderid and productid=@productID and commentstatus=1
			insert ProductReview(ProductID,MemberID,Title,Body,Score,AddTime,IP,YesNum,NotNum,Status,MemberName,MemberScore,ReviewType,IsToMessage,OrderID,OrderNo,OrderTime,SupplierID,IsReply)values(@productID,@memberID,@title,@body,@score,getDate(),@ip,0,0,0,@membername,@memberScore,@reviewtype,@istomessage,@orderid,@orderno,@ordertime,@supplierID,0)
			update orderproduct set commentstatus=2 where  orderProductID=@orderProductID
			select @errorFlag=0,@errorMessage='感谢您的评论,审核后显示'
		end
	end
	else--在订单明细里面进行商品评价
	begin
		exec XpProc_ProductReview_Check @orderID,@orderproductid,@productid,@memberID ,@errorFlag out,@errorMessage out
		if(@errorFlag=1)
		begin
			return
		end
		begin
		begin
			select @orderNo=orderno,@orderTime=ordertime,@supplierID=supplierid from orders where orders.orderid=@orderid 
			insert ProductReview(ProductID,MemberID,Title,Body,Score,AddTime,IP,YesNum,NotNum,Status,MemberName,MemberScore,ReviewType,IsToMessage,OrderID,OrderNo,OrderTime,SupplierID,IsReply)values(@productID,@memberID,@title,@body,@score,getDate(),@ip,0,0,0,@membername,@memberScore,@reviewtype,@istomessage,@orderid,@orderno,@ordertime,@supplierID,0)
			update orderproduct set commentstatus=2 where  orderid=@orderid and orderproductid=@orderproductid
			select @errorFlag=0,@errorMessage='感谢您的评论,审核后显示'
		end
		end
	end
end


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ProductReview_Update]    脚本日期: 04/09/2012 18:28:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================  
-- Author:  <liwenhai>  
-- Create date: <2011-05-04>  
-- Description: <后台管理员对商品评价的审核>  
-- =============================================  
CREATE PROCEDURE [dbo].[XpProc_ProductReview_Update] (  
@prid int, --评论ID 
@status int, --状态
@auditor int, --审核人ID 
@auditorname varchar(20), --审核人账号 
@ip varchar(20),--审核人IP 
@remark varchar(200), 
@errorFlag int=-1 output 
)
AS
begin declare @sscore int --评分
declare @score int --赠送积分
declare @orlstatus int --更新前的状态 
declare @memberid int --评价会员ID
declare @productid int --评价的商品ID 
select @memberid=memberid,@orlstatus=status,@sscore=score,@score=memberscore,@productid=productid from productreview  where productreviewid = @prid

begin try
begin tran 
--第一种status由0改为1，只需更新评论状态
print('更新评论状态') 
update productreview set status=@status, Auditor=@auditor, AuditorName=@auditorname, AuditorIP=@ip, AuditTime=getdate(),  AuditRemark=@remark where  productreviewid = @prid
if(@orlstatus<>2 and @status=2)--审核通过
begin 
	if(@score<>0)--评价有赠送积分
	begin 
	print('第一次审批通过时给会员加积分')
--		update member set score=score+@score where memberid=@memberid 会员表的积分计算放在存储过程XpProc_ScoreLog_Insert中计算
		exec XpProc_ScoreLog_Insert @memberid,null,@score,1,1,0,null,'审核通过',@prid,'发表商品评论获得积分','发表商品评论获得积分',@ip,null,null,@auditor,@auditorname
    end
    print('加评论数')
	if(@sscore=1)
	begin
		update product set reviews=isnull(reviews,0)+1,pj5=isnull(pj5,0)+1 where productid=@productid  
	end
	else if(@sscore=2)
	begin
		update product set reviews=isnull(reviews,0)+1,pj4=isnull(pj4,0)+1 where productid=@productid
	end
	else if(@sscore=3)
	begin
		update product set reviews=isnull(reviews,0)+1,pj3=isnull(pj3,0)+1 where productid=@productid  
	end 
	else if(@sscore=4)
	begin
		update product set reviews=isnull(reviews,0)+1,pj2=isnull(pj2,0)+1 where productid=@productid  
	end 
	else 
	begin 
		update product set reviews=isnull(reviews,0)+1,pj1=isnull(pj1,0)+1 where productid=@productid  
	end 
	print('更新商品平均评分') 
	update product set pingfen=(select cast(round(avg(score*1.0),0) as int) from productreview where status=2 and productid =@productid group by productid)  where productid = @productid
end
else if(@orlstatus=2 and @status<>2) --由审批通过改为未通过 
begin 
	if(@score<>0)--评价有赠送积分
	begin 
	print('由审批通过改为未通过要减去赠送的积分')
--		update member set score=score-@score where memberid=@memberid 会员表的积分计算放在存储过程XpProc_ScoreLog_Insert中计算
		exec XpProc_ScoreLog_Insert @memberid,null,@score,-1,1,0,null,'审核不通过',@prid,'冻结商品评论减去积分','冻结商品评论减去积分',@ip,null,null,@auditor,@auditorname
    end
    print('减评论数')
	if(@sscore=1) 
	begin 
		update product set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end),pj5=(case when (pj5-1>0) then (pj5-1) else 0 end) where productid=@productid  
	end 
	else if(@sscore=2) 
	begin
		update product set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end),pj4=(case when (pj4-1>0) then (pj4-1) else 0 end) where productid=@productid 
	end
	else if(@sscore=3) 
	begin
		update product set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end),pj3=(case when (pj3-1>0) then (pj3-1) else 0 end) where productid=@productid 
	end 
	else if(@sscore=4) 
	begin 
		update product set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end),pj2=(case when (pj2-1>0) then (pj2-1) else 0 end) where productid=@productid 
	end 
	else 
	begin 
		update product set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end),pj1=(case when (pj1-1>0) then (pj1-1) else 0 end) where productid=@productid  
	end
	print('更新商品平均评分') 
	update product set pingfen=(select cast(round(avg(score*1.0),0) as int) from productreview where status=2 and productid =@productid group by productid)  where productid = @productid
end
select @errorFlag=0
commit 
end try
begin catch
rollback
select @errorFlag=1
end catch
End
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ProductSelectByFenYe]    脚本日期: 04/09/2012 18:28:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ProductSelectByFenYe]
(
@pagerows int,        --每页行数    
@pageindex int,        --索引
@tab nvarchar(250),    --表名
@keyid nvarchar(50),    --主键
@total nvarchar(4000),    --条件
@sort nvarchar(50),    --排序
@kid nvarchar(500),    --列名
@tt  nvarchar(50), --针对获得总条数时需要的特殊条件，一般为*
@rows int output --总行数
)
as
begin
set nocount on
declare 
@befrows int,
@sql nvarchar(4000)
set @befrows=@pagerows*(@pageindex-1)
set @sql='select top '+cast(@pagerows as nvarchar(50))+' '+@kid+' from '+@tab+' where '+@total+' and '+@keyid+' not in (select top '+cast(@befrows as nvarchar(50))+' '+@keyid+' from '+@tab+' where '+@total+' '+@sort+' )   '+@sort+''
--insert into listpage (strsql) values(@sql)
---test
--insert into aa values(1,@sql)
EXEC (@sql)
--print @sql
-------总条数------
set @sql=N'select @rows=count('+@tt+') from '+@tab+' where '+@total+'  '+''
exec sp_executesql @sql,N'@rows int out',@rows out
select  @rows
return @rows
end

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ProductStatistics_Select]    脚本日期: 04/09/2012 18:28:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-04-28>
-- Description:	<用于商品统计，统计出商家的产品在一段时间内的销量>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ProductStatistics_Select] (
@pageIndex int,
@pageSize int,
--@ordersort varchar(20),
@sid int =-1 , --商家ID
@pid varchar(8000) ,
@start DateTIme, --商品销量统计的起始时间
@end DateTIme ,----商品销量统计的结束时间
@totalCount int =null output,
@errorflag int =null output,
@errormsg varchar(200)=null output
)
AS
Begin
set nocount on

select @errorflag=0,@errormsg=''
if isnull(@pageIndex,0) > 0
select @pageIndex=@pageIndex-1
else
select @pageIndex=0

declare @befrows int
set @befrows=@pageSize*@pageIndex

--款到发货 0未付款 1部分付款 2已付款 3已确认 4正在配货 5部分发货 6已发货 7已签收 8已退单 9已退款 10已取消 11交易失败 12已归档            }
--货到付款 0未付款 1部分付款 2未确认 3已确认 4正在配货 5部分发货 6已发货 7已签收 8已退单 9已退款 10已取消 11交易失败 12已归档  

--通过连接Porduct subcategory orders orderproduct四表，查出商家的所有的商品及在某个时间段的销量
--select product.productid,product.productname,cname,marketprice,memberprice,isnull(a.quantity,0)as quantity,isnull(a.subprice,0)as subprice from product(nolock) left join subcategory(nolock)  on product.subcategoryid=subcategory.cid
--and product.supplierid=subcategory.sid
--left join (select productid, sum(op.quantity)as quantity,sum(subprice)as subprice from orderproduct op(nolock) join orders os(nolock) on op.orderid=os.orderid where ordertime >=@start and ordertime<@end  group by productid) as a on product.productid=a.productid
--where  product.supplierid=@sid
--order by quantity desc

--一个商家的产品及对应的店内的分类,如果@pid=-1则统计这个商家的所有的商品的销售量
select top 0 product.productid,product.productname,cname,marketprice,memberprice into #temp1 from product(nolock), subcategory(nolock)  where product.subcategoryid=subcategory.cid 
if @pid='-1'
begin
insert #temp1 select  product.productid,product.productname,isnull(cname,''),marketprice,memberprice 
from product(nolock) left join subcategory(nolock)
on product.subcategoryid=subcategory.cid and product.supplierid=subcategory.sid 
where product.supplierid=@sid
end
else
begin
select * into #temp4 from dbo.func_splitint(@pid)
insert #temp1 select  product.productid,product.productname,isnull(cname,''),marketprice,memberprice 
from product(nolock) left join subcategory(nolock)
on product.subcategoryid=subcategory.cid and product.supplierid=subcategory.sid 
join #temp4
on product.productid=#temp4.val
where product.supplierid=@sid
end

--连接Orders OrderProduct二个表，找出商品在某个时间段的内的总的销量及总额
select productid, sum(op.quantity)as quantity,sum(subprice)as subprice into #temp2 
from orderproduct op(nolock) join orders os(nolock) on op.orderid=os.orderid 
where DateDiff(day, os.ordertime, @start) <1 and DateDiff(day, os.ordertime, @end)>-1 and os.status in(6,7,12) 
group by productid 
--通过temp1左连接temp2 得到商家的商品在某个时间段的内的总的销量及总额
select #temp1.*,isnull(quantity,0)as quantity,isnull(subprice,0)as subprice into #temp3 
from #temp1  join #temp2 on #temp1.productid=#temp2.productid  order by quantity desc

select top (@pageSize) *from #temp3 where productid not in (select top (@befrows) productid 
from #temp3 order by quantity desc)
select @totalcount=count(*) from #temp3
End


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ProductStorage_Update]    脚本日期: 04/09/2012 18:28:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-12-31>
-- Description:	<更新商品库存，要更新product,goods表中的库存数量及更新Product表中的Skumap>
-- Debug:
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ProductStorage_Update]
	@productids varchar(8000)=null,
	@goodsids varchar(8000)=null,
	@quantitys varchar(8000),--更新的库存数量
	@flags varchar(8000),---1是减库存 1是加库存
	@errorflag int=null output,
	@errormsg varchar(200)=null output
AS
begin
set nocount on
select @errorflag=1
select @errormsg=''
Begin try
begin tran

--@flags,加减库存的标识，从盘点库存里传过来的@flags是一串的，一个商品对应一个标识，有可能有些商品是加库存，有些商品是减库存的，
--@flags=1或-1 说明所有的商品都是要么加库存要么减库存，比较从取消订单那里传来的值就是只是1，表示要增加商品的库存。
create table #t1 (goodsid int,flag int,quantity int)
if @flags='1'
begin
insert #t1 select a.value as 'goodsID',1,c.value as 'quantity'
from
(select *from dbo.SplitToTable_Func(@goodsids,','))a,
(select *from dbo.SplitToTable_Func(@quantitys,','))c
where a.id=c.id
end
else if @flags='-1'
begin
insert #t1 select a.value as 'goodsID',-1,c.value as 'quantity'
from
(select *from dbo.SplitToTable_Func(@goodsids,','))a,
(select *from dbo.SplitToTable_Func(@quantitys,','))c
where a.id=c.id
end
else
begin
insert into #t1
select a.value as 'goodsID',b.value as 'flag',c.value as 'quantity'
from
(select *from dbo.SplitToTable_Func(@goodsids,','))a,
(select *from dbo.SplitToTable_Func(@flags,','))b,
(select *from dbo.SplitToTable_Func(@quantitys,','))c
where a.id=b.id and b.id=c.id
end

--更新货品的库存
update goods set storage= case flag when 1 then storage+quantity when -1 then storage-quantity end
from goods g,#t1 t
where g.goodsid=t.goodsid

--更新商品的库存
--要更新的商品表的的Productid
select distinct(productid) into #t2 from goods g(nolock),#t1 where g.goodsid=#t1.goodsid
--重新统计product表中的库存数量，因为相关的商品goods表中的库存已有变化
UPDATE product
SET product.storage= a.storage
from 
(SELECT g.productid,sum(isnull(storage,0))storage 
FROM goods g(nolock),#t2
where g.productid=#t2.productid
GROUP BY g.productid )a
WHERE product.Productid = a.Productid

--更新Product表中的Skumap
declare @productid int,@skumap varchar(8000),@propid varchar(50),@goodsid int,@goodsprice decimal(18,2),@goodsstock int,@goodsno varchar(50)
declare products_items_cursor cursor for
select productid from #t2
open products_items_cursor
fetch next from products_items_cursor into
@productid
while @@fetch_status=0
begin
	--构造SkuMap并更新到商品表
	declare goods_items_cursor cursor for                                                    
	select goodsid,goodsno,memberprice,storage,isnull(props,'0:0;0:0')
	from goods
	where productid=@productid
	order by goodsid asc
	select @skumap='{'
	--遍历游标
	open goods_items_cursor                                                    
	fetch next from goods_items_cursor into 
	@goodsid,@goodsno,@goodsprice,@goodsstock,@propid
	while @@fetch_status = 0                        
	begin 
	select @skumap=@skumap+'"'+@propid+'":{"skuId":"'+cast(@goodsid as varchar(50))+'","price":"'+cast(@goodsprice as varchar(50))+'","stock":"'+cast(@goodsstock as varchar(50))+'","code":"'+@goodsno+'"},'
	fetch next from goods_items_cursor into 
	@goodsid,@goodsno,@goodsprice,@goodsstock,@propid
	end
	set @skumap=STUFF(@skumap,len(@skumap),1,'}')
	update product set skumap=@skumap where productid=@productid
	--遍历结束
	close goods_items_cursor                                                    
	deallocate goods_items_cursor
	fetch next from products_items_cursor into @productid
end                                           
close products_items_cursor   
deallocate products_items_cursor
select @errorflag=0
select @errormsg='成功更新商品库存'
commit tran
End Try
Begin Catch
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
declare @err varchar(1000),@severity int 
set @err=ERROR_MESSAGE();
set @severity=ERROR_SEVERITY();
RAISERROR(@err,@severity,1);
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Prop_Delete]    脚本日期: 04/09/2012 18:28:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-08-06>
-- Description:	<删除规格项>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Prop_Delete]
@pid int,
@errorflag int out,--错误标志
@errormsg varchar(200) out--错误信息描述
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
begin tran
delete from propvalue where pid=@pid
delete from prop where pid=@pid
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PropValue_Add]    脚本日期: 04/09/2012 18:28:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-08-06>
-- Description:	<添加规格值>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PropValue_Add]
@vname varchar(50),--名称
@alias varchar(50),--别名
@remark varchar(50),--备注
@pid int,--所属规格项ID
@errorflag int out,--错误标志
@errormsg varchar(200) out--错误信息描述
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
declare @sort int
select @sort=count(1)+1 from propvalue where pid=@pid
insert into propvalue(vname,alias,remark,pid,pname,sort) select @vname,@alias,@remark,@pid,p.pname,@sort from prop p(nolock) where p.pid=@pid
End Try

Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_PropValueSort_Update]    脚本日期: 04/09/2012 18:29:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-08-09>
-- Description:	<更改规格值排序>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_PropValueSort_Update]
@vids varchar(8000),--规格值ID字符串
@sorts varchar(8000),--序号字符串
@errorflag int out,--错误标志
@errormsg varchar(200) out--错误信息描述
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
select * into #v from dbo.SplitToTable_Func(@vids,',')
select * into #s from dbo.SplitToTable_Func(@sorts,',')
select v.value as vid,s.value as sort into #pv from #V v,#s s where v.id=s.id
update p set p.sort=pv.sort from propvalue p(nolock),#pv pv where p.vid=pv.vid
End Try

Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ReceivePay_Add]    脚本日期: 04/09/2012 18:29:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-09-23>
-- Description:	<后台退款管理中提交退款信息，要调用此存储过程向ReceivePay插入退款信息>
-- Debug:
/*
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ReceivePay_Add]
	@refundtype int,--退款方式：1退款至账户余额2退款至银行卡 
	@orderNo varchar(50)=null,
	@bank varchar(50) = NULL,
	@bankAccount varchar(50) = NULL,
	@PayerName varchar(50) = NULL,
	@money money= NULL,
	@paymethod int=null,
	@paymentname varchar(50)=null,
	@WorkPeople varchar(50)=null,
	@paytime datetime =null,
	@status int =null,
	@remark varchar(200)=null,
	@isreceive bit=null,
	@OutTradeNo varchar(50)=null,
	@paybank varchar(50)=null,
	@PayBankAccount varchar(50)=null,
	--更新AppRefund用到
	@aid int=null,
	@ano varchar(20)=null,
	@adminID int=null,
	@realname varchar(50)=null,
	@errorflag int output,
	@errormsg varchar(200) output
AS
begin
set nocount on
Begin try
begin tran
--insert log(content)values(@refundtype)
if @refundtype=1--退款至账户余额
begin
--写预付款
declare @memberid int--要退款的会员ID
select @memberid=memberid from appform(nolock) where aid=@aid
declare @usedremark varchar(100)
select @usedremark ='订单[' +@orderno+']退款，增加会员账户余额'
exec XpProc_AdvancePayment_Add @memberid,null,@money,1,@realname,@usedremark,@errorflag out,@errormsg out
--插入退款记录
INSERT ReceivePay(
OrderNo, Bank, BankAccount, PayerName, [Money], PayMethod,PaymentName, WorkPeople,  
PayTime, Status, Remark, IsReceive,OutTradeNo, PayBank, PayBankAccount)
VALUES (
@OrderNo, @bank, @bankAccount, @workPeople, @money, @payMethod,@paymentname, @workPeople, 
getDate(),COALESCE(@Status, (1)), @remark, @IsReceive, @outTradeNo, @payBank, @payBankAccount)
end
else --退款到银行卡账号
begin
--插入退款记录
INSERT ReceivePay(
OrderNo, Bank, BankAccount, PayerName, [Money], PayMethod,PaymentName, WorkPeople,  
PayTime, Status, Remark, IsReceive,OutTradeNo, PayBank, PayBankAccount)
VALUES (
@OrderNo, @bank, @bankAccount, @payerName, @money, @payMethod,@paymentname, @workPeople, 
@payTime,COALESCE(@Status, (1)), @remark, @IsReceive, @outTradeNo, @payBank, @payBankAccount)
end

--更新AppRefund的状态
exec XpProc_AppRefund_Update @aid,@ano,@adminid,@realname,'isrefund',null,@remark,@errorflag output,@errormsg output
select @errorFlag=0
select @errorMsg='操作成功'
commit tran
End Try

Begin Catch
rollback tran
-- 捕捉错误
select @errorFlag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
End Catch
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ReceivePay_Insert]    脚本日期: 04/09/2012 18:29:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Hakkas@qq.com>
-- Create date: <2011-06-14>
-- Description:	<添加收款纪录>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ReceivePay_Insert]
	@OrderNo varchar(50) = NULL,--订单编号
	@MemberName varchar(50) = NULL,--订单会员账户
	@Bank varchar(50) = NULL,--收款银行名称
	@BankAccount varchar(50) = NULL,--收款账号
	@PayerName varchar(50) = NULL,--付款人姓名
	@Money money = NULL,--付款金额
	@PayMethod int = NULL,--支付类型:1在线支付，2线下支付，3预付款支付
	@PaymentName varchar(50) = NULL,--支付方式名称
	@WorkPeople varchar(50) = NULL,--操作人
	@PayTime datetime = NULL,--付款时间
	@AddTime datetime = NULL,--添加时间
	@Status int = NULL,--状态
	@Remark varchar(255) = NULL,--备注
	@IsReceive bit = NULL,--是收款还是退款
	@OutTradeNo varchar(50) = NULL,--外部交易号
	@PayBank varchar(50) = NULL,
	@PayBankAccount varchar(50) = NULL,
	@errorFlag int,--错误标志
	@errorMsg varchar(200)--错误提示
AS
Begin Try
INSERT ReceivePay(
OrderNo, MemberName, Bank, BankAccount, PayerName, [Money], PayMethod,PaymentName, WorkPeople,  --1
PayTime, AddTime, Status, Remark, IsReceive,OutTradeNo, PayBank, PayBankAccount)--2
VALUES (
@OrderNo, @MemberName, @Bank, @BankAccount, @PayerName, @Money, @PayMethod,@PaymentName, @WorkPeople, --1
@PayTime, COALESCE(@AddTime, getdate()), COALESCE(@Status, (1)), @Remark, @IsReceive, @OutTradeNo, @PayBank, @PayBankAccount)--2
select @errorFlag=0,@errorMsg=''
RETURN SCOPE_IDENTITY()
End Try

Begin Catch
-- 捕捉错误
--print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
--print @errormsg
Return -1
End Catch


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ReceiverAddress_Insert]    脚本日期: 04/09/2012 18:29:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-06-04>
-- Description:	<添加地址簿>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ReceiverAddress_Insert]
	@ReceiverName nvarchar(50),
	@ReceiverAddress nvarchar(200),
	@ReceiverZip nvarchar(50),
	@ReceiverPhone nvarchar(50),
	@ReceiverMobile nvarchar(50),
	@MemberID int,
	@AddressID nvarchar(50),
	@ReceiverEmail varchar(50)
AS

INSERT ReceiverAddress(ReceiverName, ReceiverAddress, ReceiverZip, ReceiverPhone, ReceiverMobile, MemberID, AddressID,ReceiverEmail)
VALUES (@ReceiverName, @ReceiverAddress, @ReceiverZip, @ReceiverPhone, @ReceiverMobile, @MemberID, @AddressID,@ReceiverEmail)

RETURN SCOPE_IDENTITY()




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ReceiverAddress_Update]    脚本日期: 04/09/2012 18:29:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-10-26>
-- Description:	<更改地址簿>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ReceiverAddress_Update]
@ReceiverAddressID int,
@ReceiverName nvarchar(100),
@ReceiverAddress nvarchar(400),
@ReceiverZip nvarchar(100),
@ReceiverPhone nvarchar(100),
@ReceiverMobile nvarchar(100),
@MemberID int,
@AddressID nvarchar(100),
@ReceiverEmail varchar(50) = NULL
AS

UPDATE	ReceiverAddress
SET	ReceiverName = @ReceiverName,
	ReceiverAddress = @ReceiverAddress,
	ReceiverZip = @ReceiverZip,
	ReceiverPhone = @ReceiverPhone,
	ReceiverMobile = @ReceiverMobile,
	MemberID = @MemberID,
	AddressID = @AddressID,
	ReceiverEmail = @ReceiverEmail
WHERE 	ReceiverAddressID = @ReceiverAddressID



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Role_Add]    脚本日期: 04/09/2012 18:29:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-9-16>
-- Description:	<添加角色>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Role_Add] 
@rolename varchar(50),--角色名称
@remark varchar(200),--备注
@status int,--状态
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
begin tran
insert into [role](rolename,remark,status) values(@rolename,@remark,@status)
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Role_Delete]    脚本日期: 04/09/2012 18:29:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-9-16>
-- Description:	<删除角色>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Role_Delete] 
@roleid int,--角色ID
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
begin tran
delete from [role] where roleid=@roleid
delete from rolepermission where roleid=@roleid
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Role_Update]    脚本日期: 04/09/2012 18:29:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-9-16>
-- Description:	<修改角色>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Role_Update] 
@roleid int,--角色ID
@rolename varchar(50),--角色名称
@remark varchar(200),--备注
@status int,--状态
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
begin tran
update [role] set rolename=@rolename,remark=@remark,status=@status where roleid=@roleid
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_RolePermission_Add]    脚本日期: 04/09/2012 18:29:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-9-16>
-- Description:	<添加角色权限关联>
/*
debug:exec XpProc_RolePermission_Add 1,'admin','1,2,3,4,5'
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_RolePermission_Add] 
@roleid int,--角色ID
@adduser varchar(50),--添加人
@pids varchar(8000),--权限ID
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
begin tran
delete from RolePermission where roleid=@roleid
select * into #p from SplitToTable_Func(@pids,'|')
select p.pid into #r from #p,permission p(nolock) where p.permission=#p.value
insert into RolePermission(roleid,pid,adduser) select @roleid,r.pid,@adduser from #r r
commit
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch

END



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_RolePermission_Get]    脚本日期: 04/09/2012 18:29:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-09-15>
-- Description:	<获取角色权限>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_RolePermission_Get]
@roleid int,
@rolename varchar(20) output
AS
BEGIN
--获取角色名
select @rolename=rolename from [role] where roleid=@roleid
--获取角色权限集合
select p.permission
from rolepermission rp(nolock),permission p(nolock)
where rp.roleid = @roleid and rp.pid=p.pid

--select @power=@power+'|'+p.permission
--from rolepermission rp(nolock),permission p(nolock)
--where rp.roleid = @roleid and rp.pid=p.pid
--select @power=stuff(@power,1,1,'')
END

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ScoreLog_Init]    脚本日期: 04/09/2012 18:29:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-07-14>
-- Description:	<会员中心查看我的积分>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ScoreLog_Init]
	@memberid int,--会员ID
	@flag int=99999,--获取积分标志：1获得的积分记录；-1使用掉的积分记录
	@pageno int=1,--页码
	@pagesize int=15,--每页显示记录数
	@consumescores int output,--消费的积分
    @getscores int output,--获得的积分
	@totalscores int output,--获得的积分
	@totalcount int output,--总记录数
	@totalpage int output----总页数
AS
BEGIN
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

--获取消费积分总额
select @consumescores=sum(score) from xpscorelog where memberid=@memberid and flag=-1
--获取获得积分总额
select @getscores=sum(score) from xpscorelog where memberid=@memberid and flag=1
--获得可用积分总额
select @totalscores=sum(score) from xpscorelog where memberid=@memberid

--获取积分记录
declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' memberid='+convert(varchar(20),@memberid)

if isnull(@flag,99999)<>99999
select @where=@where+' and flag='+convert(varchar(20),@flag)

select @sqlstr='select rowno,SLID,score,flag,totalscore,GenerateTime,addusername,remark from (
select SLID,abs(score) as score,flag,totalscore,GenerateTime,addusername,remark,Row_number() over(order by addtime desc) as rowno 
from xpscorelog(nolock)
where ' + @where + ') as p where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

print @sqlstr
insert into log(content) values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by addtime desc) as rowno from xpscorelog(nolock) where ' + @where + ') as p)'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

select @totalcount=isnull(@totalcount,0)
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)


--select * from xpscorelog where memberid=@memberid and flag=case when @flag='in' then 1 when @flag='out' then -1 else flag end 
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ScoreLog_Insert]    脚本日期: 04/09/2012 18:29:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-07-07>
-- Description:	<添加积分日志>
/*
引用该存储过程的存储过程：
1、XpProc_Member_Insert
2、XpProc_Order_Make
3、XpProc_ProductReview_Update
4、[XpProc_ProductReview_Delete
*/
/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20111115                              
content:                                
1.xpScoreLog添加2个字段PreScore、TotalSocre用于存放积分变动前和变动后的积分
*/
-- =============================================
CREATE PROC [dbo].[XpProc_ScoreLog_Insert]
	@MemberID int,
	@Mobile varchar(20) = NULL,
	@Score decimal(18, 2),
	@Flag int,
	@NeedSend bit = NULL,
	@IsSended bit = NULL,
	@SendTime datetime = NULL,
	@ScoreType varchar(50) = NULL,
	@FromID varchar(100) = NULL,
	@FromRemark varchar(100) = NULL,
	@Remark varchar(200) = NULL,
	@AddIP varchar(50) = NULL,
	@GenerateTime datetime = NULL,
	@AddTime datetime = NULL,
	@AddUser int = NULL,
	@AddUserName varchar(50) = NULL	
AS
--如果是扣减积分，传过来的积分数又是正数的，要变成负数
if @Flag=-1 and @Score>0
select @Score=-@Score
--计算增加后的积分
declare @prescore int,@newscore int
select @prescore=isnull(score,0) from member(nolock) where memberid=@memberid
select @newscore=@prescore+@score
--更改会员积分
update member set score=@newscore where memberid=@memberid
--写入积分日志
INSERT xpscorelog(
MemberID, Mobile,Prescore,Score,TotalScore, Flag, NeedSend, IsSended, SendTime, ScoreType, FromID, 
FromRemark, Remark, AddIP, GenerateTime, AddTime, AddUser, AddUserName
)
VALUES (
@MemberID, @Mobile,@prescore,@score,@newscore,@Flag, COALESCE(@NeedSend, (1)), COALESCE(@IsSended, (0)), @SendTime, @ScoreType, @FromID, 
@FromRemark, @Remark, @AddIP, COALESCE(@GenerateTime, getdate()), COALESCE(@AddTime, getdate()), COALESCE(@AddUser, -1), COALESCE(@AddUserName,'system')
)






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SecKill_Add]    脚本日期: 04/09/2012 18:29:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-10-26>
-- Description:	<秒杀>
--修复秒杀BUG，处理秒杀商品由productid精确到goodsid,因为后台添加秒杀商品精确到goodsid
-- =============================================
CREATE procedure [dbo].[XpProc_SecKill_Add]
@ruleid int,
@productid int,
@goodsid int=null,
@supplierid int=0,
@memberid int,
@addip varchar(50),
@balance int output,
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
select @balance=0,@errorflag=0,@errormsg=''

Begin Try
declare @rulename varchar(100),@buyednum int,@limitednumber int,@islimited int,@ruleno varchar(20),@pmtprice decimal(18,2),@productname varchar(100),@begintime datetime,@endtime datetime
select @buyednum=0,@limitednumber=1
select @rulename=r.rulename,@balance=balance,@islimited=islimited,@limitednumber=limitednumber,@ruleno=r.ruleno,@pmtprice=g.pmtprice,@productname=g.productname,@begintime=r.begintime,@endtime=r.endtime
from pmtgoods g(nolock),pmtrule r(nolock) 
--where g.ruleid=@ruleid and g.productid=@productid and g.ruleid=r.ruleid
where g.ruleid=@ruleid and g.goodsid=@goodsid and g.ruleid=r.ruleid
--and getdate() between r.begintime and r.endtime
print('时间有效性判断开始')
if getdate()<@begintime
begin
select @errorflag=2,@errormsg='秒杀还未开始，请耐心等待'
return
end

if getdate()>@endtime
begin
select @errorflag=3,@errormsg='秒杀已结束，请等待下一期'
return
end
--insert into log(content) values ('errormag:'+@errormsg)
print('数量有效性判断开始')
--还未秒完
if @balance>0
begin
--统计该会员已秒的数量
--select @buyednum=sum(quantity) from memberbookseckill where ruleid=@ruleid and productid=@productid and memberid=@memberid
select @buyednum=sum(quantity) from memberbookseckill where ruleid=@ruleid and goodsid=@goodsid and memberid=@memberid
if @islimited=1 and @buyednum>=@limitednumber
begin
select @errorflag=4,@errormsg='对不起，您已超出限制数量'
return
end
else
begin
--符合条件，开始秒杀
--首先扣减该活动商品的剩余数量
begin tran
--update pmtgoods set balance=balance-1 where ruleid=@ruleid and productid=@productid
update pmtgoods set balance=balance-1 where ruleid=@ruleid and goodsid=@goodsid
--记录该次秒杀记录
INSERT memberbookseckill
(ruleid,rulename,ruleno, memberid, productid, goodsid,productname, quantity,pmtprice,addip,status,adduser,supplierid)
VALUES 
(@ruleid,@rulename, @ruleno, @memberid, @productid, @goodsid,@productname,1,@pmtprice,@addip,0, @memberid,@supplierid)
commit
--返回剩余数量
select @balance=@balance-1
end
end
--已秒完
else
begin
select @errorflag=5,@errormsg='对不起，已秒完'
return
end
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=6
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SecKillMember_Get]    脚本日期: 04/09/2012 18:29:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-05-21>
-- Description:	<会员中心分页获取我的秒杀>
-- Debug:

-- =============================================
CREATE PROCEDURE [dbo].[XpProc_SecKillMember_Get]
@status int,
@memberid int,--会员id
@pagesize int=10,--每页显示商品数
@pageno int=1,--页码
@totalpage int output,--总页数
@totalcount int output,--总记录数
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

Begin Try
declare @sqlstr nvarchar(4000),@where nvarchar(4000),@sort varchar(50)
select @sort=' order by addtime desc'
select @where = ''

select @status=isnull(@status,0)
select @where=@where+' status='+convert(varchar(10),@status)
select @where=@where+' and memberid='+convert(varchar(20),@memberid)

select @sqlstr='select rowno,uid,ruleno,productid,goodsid,productname,pmtprice,orderno,ordertime,addtime from (
select uid,ruleno,productid,goodsid,productname,pmtprice,orderno,ordertime,addtime,Row_number() over('

if isnull(@sort,'')<>''
select @sqlstr=@sqlstr+@sort
else
select @sqlstr=@sqlstr+'order by addtime desc'

select @sqlstr=@sqlstr+ ') as rowno 
from MemberBookSecKill(nolock)'

select @sqlstr=@sqlstr+' where ' + @where + ') as l where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))

--print @sqlstr
--insert into log(content) values(@sqlstr)
Execute(@sqlstr)

--获取总记录数和总页数

select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by uid desc) as rowno from MemberBookSecKill(nolock)'
select @sqlstr=@sqlstr++' where ' + @where + ') as l )'
--print @sqlstr
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output

if(isnull(@totalcount,0)=0)
select @totalcount=0
select @totalpage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)
--select @totalcount,@totalpage
End Try

Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @totalcount=0
select @totalpage=0
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return
End Catch
 
END











GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ShippingPrice_Select]    脚本日期: 04/09/2012 18:29:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-09>
-- Description:	<用于商家后台，配送费用的获取>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ShippingPrice_Select] (
@sid int =-1 , --商家ID
--@totalCount int output,
@parentid int =-1, --一级地区ID
@shippingid int=-1 --快递ID
)
AS
Begin
--insert log (content)values(cast(@parentid as char(10))+'s'+cast(@shippingid as varchar(10)))
--select *from log order by addtime desc
   --绑定一级地区
	--table[0] 一级地区列表
	select * from ShippingArea(nolock) where parentid=0
	select shippingid,name from Shipping(nolock)

	if(@parentid>0)
    --绑定二级地区
	begin
	--先在ShippingPrice 表中查找，没有纪录时再去Shipping 中查找
	--一个一级地区下的二级地区的配送费用公式，首先要在ShippingPrice表中查找
	select shippingarea.ShippingAreaID,ShippingAreaNo,shippingarea.name,parentno,sort,shippingexpression,shippingid=@shippingid,isnull(shippingpriceid,0)as shippingpriceid into #temp
	From shippingarea(nolock) left join shippingprice(nolock) 
	on shippingarea.ShippingAreaID=shippingprice.ShippingAreaID and shippingid=@shippingid and supplierid=@sid where ParentNo=dbo.f_GetShippingAreaNo(@parentid) or ShippingArea.ShippingAreaID=@parentid
	
		--shippingpriceid=0,说明没有设定新的配送方式，还要去Shipping中去查找默认的配送费用
		if exists (select * from #temp where shippingpriceid=0)
		begin
			--如果商家没有设置配送方式的话，默认得到supplierid=0的配送方式
--			if not exists(select *from shipping where supplierid=@sid)
--			set @sid=0
			--table[2]二级地区，某类快递的默认配送公式
			select ShippingAreaID,ShippingAreaNo,#temp.name,parentno ,sort,case when shippingexpression is null then price else shippingexpression end as shippingexpression ,shippingpriceid,#temp.shippingid from #temp left join shipping on #temp.shippingid=shipping.shippingid and supplierid=0
		end
		else
		begin
			select ShippingAreaID,ShippingAreaNo,name,parentno ,sort,shippingexpression,shippingpriceid,shippingid from #temp
		end
	end

End

--EXEC XpProc_ShippingPrice_Select 10001,19,3


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ShippingPrice_Update]    脚本日期: 04/09/2012 18:29:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-09>
-- Description:	<用于商家后台配送费用管理 ，配送费用的设置>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ShippingPrice_Update] (
@sid int =-1 , --商家ID
@shippingareaids varchar(200), --地区ID集
@shippingexpression varchar(1024),--配送公式集
@shippingid int,--配送方式ID
@shippingpriceids varchar(200),--自定义配送公式的ID
@errorFlag int =-1 out--是否错误标识
)
AS
Begin
begin tran
select * into #temp1 from dbo.func_splitint2(@shippingareaids )--地区ID集转成表格形式
select * into #temp2 from dbo.func_SplitChar(@shippingexpression,',' )--配送公式
select * into #temp3 from dbo.func_splitint2(@shippingpriceids)--自定义配送公式的ID
select #temp1.value as shippingareaid,#temp2.value as shippingexpression,#temp3.value as shippingpriceid into #temp4 from #temp1 join #temp2 on #temp1.id=#temp2.id join #temp3 on #temp3.id=#temp1.id

--当shippingpriceid=0，说明这条数据是要插入到ShippingPrice表中去的,否则只是更新ShippingPrice表
select * into #temp5 from #temp4 where #temp4.ShippingPriceID=0
select * into #temp6 from #temp4 where #temp4.ShippingPriceID<>0


--用#temp6中表的数据批量更新ShippingPrice表中的数据
if exists(select top 1 * from #temp6)
update  shippingprice set ShippingExpression=#temp6.shippingexpression from #temp6 ,shippingprice where #temp6.shippingpriceid=shippingprice.shippingpriceid

--用#temp5中表的数据批量插入到ShippingPrice表
if exists(select top 1 * from #temp5)
insert into shippingprice(shippingareaid,shippingid,shippingexpression,supplierid) select shippingareaid,@shippingid, shippingexpression,@sid from #temp5
--insert log (content)values(cast(@sid as char)+cast(@shippingareaids as char)+cast(@shippingexpression as char)+cast(@shippingid as char)+cast(@shippingpriceids as char))
--select * from log order by addtime desc
set @errorFlag=0
commit tran
End
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ShipPrice_Get]    脚本日期: 04/09/2012 18:29:13 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
-- =============================================
-- Author:		<hakkas>
-- Create date: <2010-10-01>
-- Description:	<运费计算>
/*
引用该存储过程的存储过程：
1、XpProc_CartShipPrice_Get
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ShipPrice_Get] 
@subAreaID int=-1,--市级地区ID
@shippingID int,--配送方式ID
@weight decimal(18,2),--商品总重量
@sid int,--商家ID
@shipPrice decimal(18,2) out--返回配送价格
AS
--ShippingExpression=18+(c(w/110)-1)*6
declare @exp nvarchar(100),--运费公式
@sql nvarchar(1000)
--从地区配送价格公式表获取对应的配送价格公式
select @exp=lower(ShippingExpression) from ShippingPrice(nolock) where ShippingAreaID=@subAreaID and ShippingID=@shippingID and supplierid=@sid
if isnull(@exp,'')=''
begin
--未设置地区配送价格公式，则取配送方式的默认配送价格
select @exp=lower(price) from Shipping(nolock) where ShippingID=@shippingID -- and supplierid=@sid
--没有配送方式的，取默认配送价格15
select @exp=isnull(@exp,'15')
end

select @exp=replace(@exp,'c','ceiling')
select @exp=replace(@exp,'w',cast(@weight as nvarchar(20)))
select top 0 shiprice=convert(money,0.0) into #shiprice
select @sql=N'insert into #shiprice select '+@exp
exec sp_executesql @sql
select @shipPrice=shiprice from #shiprice


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ShopEval_Check]    脚本日期: 04/09/2012 18:29:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-13>
-- Description:	<用于会员中心，根据订单ID，验证会员是否可以对某个商家进行评价>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ShopEval_Check] (
@orderID int,--订单ID
@memberID int,--会员ID
@isErrorFlag int=0 out,     --是否错误标识，<>0 时，显示错误信息
@errorMessage nvarchar(100)='' out   --错误信息提示 
)
AS
begin
	--只有这个订单是属于这个会员，且状态为12时，这个会员才可以评价这个商家
	if not exists(select * from orders where orderid=@orderid and memberid=@memberid and status in(12))
	begin
	select @isErrorFlag=1,@errorMessage='这次交易还不能评价商家！'
	return
	end
	if exists(select * from shopEval where orderid=@orderID)
	select @isErrorFlag=1,@errorMessage='您这次交易已评价过商家！'
	else
	select @isErrorFlag=0,@errorMessage='你已完成这宗交易可以评价商家'
end







GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ShopEval_Delete]    脚本日期: 04/09/2012 18:29:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-12>
-- Description:	<后台管理员，删除会员对商家的评价>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ShopEval_Delete] (
@seids int,--商家评价ID 
@isErrorFlag int =-1 output)
as 

Begin
set nocount on
declare @score int --赠送积分
declare @orlstatus int --更新前的状态 
declare @memberid int --评价会员ID
declare @supplierid int --商家ID 
select @memberid=memberid,@orlstatus=status,@score=memberscore,@supplierid=supplierid from ShopEval  where ShopEvalID = @seids
set @isErrorFlag=-1
begin tran
--评价有回复时要删除回复
delete from EvalReply Where ShopEvalID in (@seids)
--删除的评价，有三种情况：未审核，已审核未通过，已审核通过
if(@orlstatus=2)--已审核的评价
begin 
--    print('减评论数')
--	update supplier set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end) where supplierID=@supplierID
	print('删除评价')
	delete from ShopEval where ShopEvalID=@seids
	--用PJ1来保存顾客对商家的评价的平均分数，每次删除记录时要更新此值
	print('减评论数,更新商家的评价平均评分') 
	--取得最新的评价分数
	declare @pj1 decimal,@pj2 decimal,@pj3 decimal,@pj4 decimal,@pingfen decimal
	select @pj1=avg(pj1),@pj2=avg(pj2) ,@pj3=avg(pj3) ,@pj4=avg(pj4),
	@pingfen=avg(pingfen)from shopeval  where status=2 group by supplierid  having supplierid=@supplierid
	update Supplier set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end),pj1=isnull(@pj1,0),pj2=isnull(@pj2,0),pj3=isnull(@pj3,0),pj4=isnull(@pj4,0),pingfen=isnull(@pingfen,0) where supplierID=@supplierID
end
--否则删除的是未审核或审核未通过的，不用更改评价数，评价平均分
else
begin
	print('删除评价')
	delete from ShopEval where ShopEvalID=@seids
end
set @isErrorFlag=0
commit
End















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ShopEval_Insert]    脚本日期: 04/09/2012 18:29:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-12>
-- Description:	<会员对购买过的某个商家的评价>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ShopEval_Insert] (
@memberID int,--评论者ID
@title varchar(510), --评价标题
@body ntext,--评价内容
@ip varchar(40),--评价人IP
@memberName varchar(100), --评论人账号
@memberScore int,--会员积分 
@isToMessage tinyint, --是否发送至小信使
@orderID int,--订单ID
@pj1 decimal(18,2),--评价1
@pj2 decimal(18,2),--评价2
@pj3 decimal(18,2),--评价3
@pj4 decimal(18,2),--评价4
@isErrorFlag int =0 out,     --是返回0表示增加成功，返回1表示针对这个Orderid以前已对商家进行过评价
@errorMessage nvarchar(100)='' out   --错误信息提示 
)
AS
Begin
--declare @orderNo varchar(100)--订单号
--declare @receiveTime datetime --收货时间
--declare @supplierid int --商家ID
--在商家评价记录表中，没有对应的orderID,表示此这交易还没有对商家进行评价。
if not exists(select ShopEvalID from shopEval(nolock) where orderid = @orderid )
begin
declare @pingfen decimal(18,2)
set @pingfen=(@pj1+@pj2+@pj3+@pj4)/4 --评价的平均分
insert shopEval(MemberID,Title,Body,AddTime,IP,YesNum,NotNum,Status,MemberName,MemberScore,IsToMessage,OrderID,OrderNo,ReceiveTime,SupplierID,IsReply,Auditor,AuditorName,AuditTime,AuditorIP,AuditRemark,pj1,pj2,pj3,pj4,pingfen)
select @memberID,@title,@body,getDate(),@ip,0,0,0,@membername,0,@istomessage,orderid,orderno,receiveTime,supplierID,0,null,null,null,null,null,@pj1,@pj2,@pj3,@pj4,@pingfen from orders where orderid=@orderid
select @isErrorFlag=0,@errorMessage=''
end
else
begin
	select @isErrorFlag=1,@errorMessage='您这次交易已评价过商家！'
end
End






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ShopEval_Select]    脚本日期: 04/09/2012 18:29:15 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-04-27>
-- Description:	<商家后台根据ShopEvalID,EvalReply表查找对应的评价及回复>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ShopEval_Select] (
@seid int =-1 --ShopEvidID,商家评价表中的主键
)
AS
Begin
--根据ShopEvidID 得到这个评价的详情
select ShopEvalID,orderid,orderno,membername,title,body,addtime,pj1,pj2,pj3,pj4,pj5,pingfen from ShopEval(nolock) where ShopEvalID=@seid
--根据ProductReviewID 得到商家对这个评价的回复
select body,replytime,* from EvalReply (nolock) where ShopEvalID =@seid 
End
       


















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ShopEval_Update]    脚本日期: 04/09/2012 18:29:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-12>
-- Description:	<后台管理员，审核会员对商家的评价,会更新Supplier表中的评价分数以及评价数>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ShopEval_Update] (
@seid int, --商家评价ID 
@status int, --状态
@auditor int, --审核人ID 
@auditorname varchar(20), --审核人账号 
@ip varchar(20),--审核人IP 
@remark varchar(200), 
@isErrorFlag int output 
)
as 
begin
declare @sscore int --评分
declare @orlstatus int --更新前的状态 
declare @memberid int --评价会员ID
declare @supplierid int --商家ID
declare @pj1 decimal(18,2), @pj2 decimal(18,2) ,@pj3 decimal(18,2), @pj4 decimal(18,2),@pingfen decimal (18,2)

--在Supplier中存的评价平均分
select @memberid=memberid,@orlstatus=status, @supplierid=supplierid from ShopEval  where shopEvalID = @seid

begin tran 
--更新开始
print('更新评价状态，并加上审核人的信息') 
update ShopEval set status=@status, Auditor=@auditor, AuditorName=@auditorname, AuditorIP=@ip, AuditTime=getdate(),  AuditRemark=@remark where  shopEvalID = @seid
--取得最新的评价平均分数
select @pj1=avg(pj1),@pj2=avg(pj2) ,@pj3=avg(pj3) ,@pj4=avg(pj4),
@pingfen=avg(pingfen)from shopeval  where status=2 group by supplierid  having supplierid=@supplierid 
if(@orlstatus<>2 and @status=2)--审核通过
begin 
    print('加评论数，更新评价分数')
	update Supplier set reviews=reviews+1,pj1=@pj1,pj2=@pj2,pj3=@pj3,pj4=@pj4,pingfen=@pingfen where supplierID=@supplierID
end
else if(@orlstatus=2 and @status<>2) --由审批通过改为未通过 
begin
	print('减评论数，更新评价分数')
	update Supplier set reviews=(case when (reviews-1>0) then (reviews-1) else 0 end),pj1=isnull(@pj1,0),pj2=isnull(@pj2,0),pj3=isnull(@pj3,0),pj4=isnull(@pj4,0),pingfen=isnull(@pingfen,0) where supplierID=@supplierID
end
select @isErrorFlag=0
commit 
End



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_ShopEvalAndReply_Select]    脚本日期: 04/09/2012 18:29:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-05-24>
-- Description:	<用于商家店铺页，得到客户对商家的评价及商家的回复>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_ShopEvalAndReply_Select] (
@pageSize int=10,        --每页行数    
@pageNo int=1,        --当前页
@sort varchar(50), --排序字段
@sid int, --商家ID
@totalCount int=0 output,--总评价行数
@totalPage int=0 output,--总的分页数
@errorFlag int =1 output 
)
AS
Begin
--select *from log order by addtime desc
declare @befrows int
set @befrows=@pageSize*(@pageNo-1);
--分页显示客户对商家的评价

--with TempShopEval as (select ShopEvalID,MemberName,ReceiveTime,Title,Body,status ,YesNum,NotNum,pj1,pj2,pj3,pj4,pingfen,ROW_NUMBER()Over(order by @sort)as rowid from ShopEval where supplierid=@sid and status<>1)
with TempShopEval as (select ShopEvalID,MemberName,ReceiveTime,Title,Body,status ,YesNum,NotNum,pj1,pj2,pj3,pj4,pingfen,
--ROW_NUMBER()Over(order by @sort)as rowid 
CASE @sort 
        WHEN '0' THEN (ROW_NUMBER() OVER(ORDER BY ShopEvalID desc))
        WHEN '1' THEN (ROW_NUMBER() OVER(ORDER BY PingFen desc))
        WHEN '2' THEN (ROW_NUMBER() OVER(ORDER BY YesNum desc))
end as rowid
from ShopEval where supplierid=@sid and status=2)
Select  top (@pageSize)* into #TempShopEval from TempShopEval where rowid>@befrows ORDER BY rowid 
--Select * into #TempShopEval from TempShopEval where rowid BETWEEN @befrows AND @befrows + @pageSize ORDER BY rowid

Select * from #TempShopEval
--insert log(content)values(@sort)
--select *from log order by addtime desc

select @totalCount=count(ShopEvalID) from ShopEval where supplierid=@sid and status=2
select @totalCount=isnull(@totalCount,0)
select @totalPage=(CASE WHEN (@totalcount % @pagesize)<>0 THEN (@totalcount/@pagesize + 1) ELSE (@totalcount/@pagesize) END)

--商家对应的回复
select  EvalReply.ShopEvalID,EvalReply.Body,ReplyTime from EvalReply ,#TempShopEval where EvalReply.ShopEvalID=#TempShopEval.ShopEvalID

--商家的基本的信息
select SupplierName,PdtNum,AddTime,Address ,Reviews,pj1,pj2,pj3,pj4,pingfen from supplier
--table[2]
--评价详情
select 评价分数,评价类型 into #temp1 from shopeval  unpivot(评价分数 for 评价类型 in([pj1],[pj2],[pj3],[pj4]))c where supplierid=@sid and status=2 order by  评价类型
--评价的数量
declare @total int
select @total=reviews from supplier where supplierid=@sid
--生成评价分数段所占的百分比
select *,count(评价分数)as itemCount,rtrim(cast (count(评价分数)*100.0/(case when @total=0 then  1  else @total end) as decimal(18,2)) )+'%' as percents into #temp2  From  #temp1 group by  评价类型,评价分数
--生成一个临时表然后与#temp2左连接
create table #temp3(评价分数 decimal(18,2),评价类型 varchar(3))
insert into  #temp3
select 1.00,'pj1'  union all
select 2.00,'pj1'  union all
select 3.00,'pj1'  union all
select 4.00,'pj1' union all
select 5.00,'pj1' union all
select 1.00,'pj2' union all
select 2.00,'pj2' union all
select 3.00,'pj2' union all
select 4.00,'pj2' union all
select 5.00,'pj2' union all
select 1.00,'pj3' union all
select 2.00,'pj3' union all
select 3.00,'pj3' union all
select 4.00,'pj3' union all
select 5.00,'pj3' union all
select 1.00,'pj4' union all
select 2.00,'pj4' union all
select 3.00,'pj4' union all
select 4.00,'pj4' union all
select 5.00,'pj4'
--返回一个总是包含20条记录的table
select #temp3.评价分数,#temp3.评价类型,isnull(itemcount,0)as itemcount,isnull(percents,0) as percents from #temp3 left join #temp2 on #temp3.评价类型=#temp2.评价类型 and #temp3.评价分数=#temp2.评价分数 order by 评价类型, 评价分数 desc
select @errorflag=0
end





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Storage_Add]    脚本日期: 04/09/2012 18:29:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<liwenhai>
-- Create date: <2010-06-20>
-- Description:	<商品的出入库记录明细，有二种情况，1是商家发货时的出库 2是商家后台入库的操作，>
-- debug:<declare @errorFlag int  exec XpProc_ProductStorage_Update '1,2,3,1,1,2,2','577,577,577,575,575,575,575','657,658,659,651,652,653,654',0,@errorFlag output  select @errorFlag>
--引用此存储过程的存储过程为：XpProc_OrderSendGoods_Add
-- =============================================

CREATE PROC [dbo].[XpProc_Storage_Add](
	@orderid int =null,--订单ID
	@goodsIDs varchar(8000)=Null,--出入库存商品货品ID的集
	@amounts varchar(8000)=Null,--出入库的商品数量,格式为'1,2,3,4,5'
	@remarks varchar(8000)=null,----出入库说明 格式为'入库1,入库2,入库3'
	@flag int =-1 ,--用于标记是入库还是出库。-1出库，1入库
	@adminid int ,--管理员ID
	--以下的系统日志用到
	@adminName varchar(20)=null, --管理员账号
	@realname varchar(20)=null, --管理员真实姓名
	@ip varchar(40)=null,--操作人IP
--	@remark ntext,--备注
	@errorFlag int=1 output --用于标识执行是否成功,0为正常结束，1为产生异常

)
AS
begin
	set @errorFlag=1
	-----------------------------------------------------
	--订单ID不为空，说明是发货时，向Storage插入出库记录
	if @orderid is not null 
	begin
	--@goodsIDs,@amountss串生成一个具有商品品ID，及数量的临时表
	select a.value as 'goodsID',b.value as 'amount',productspecs into #pdtTemp1
	from
	(select *from dbo.SplitToTable_Func(@goodsIDs,','))a,
	(select *from dbo.func_splitint2(@amounts))b,
	(select goodsid,productspecs from orderproduct(nolock) where orderid=@orderid)c
	where a.id=b.id and a.value=c.goodsid

	--向Storage表中插入商品出入库纪录
	--向库存表中插入纪录
	--当前的订单处理是每个订单生成就会减去这个商品的库存，但这实际上一个标识而已，表示这个商品将要出货的数量，
	--但直到发货前都还在库房的,因此库房出里记录的商品的库存跟Goods表记录的库存数量可能是不一致的不能直接取 goods 表
	--中的Storage
	--#pdtTemp2 orderproduct表中 商品ID及对应在orderproduct中还没发出去的总商品数量
	select goodsid ,sum(stockout)as stockout into #pdtTemp2 from orderproduct where stockout >0 
	and goodsid in(select goodsid from orderproduct(nolock) where orderid=@orderid) group by goodsid
	--#pdtTemp3 包含商品ID及对应在orderproduct中还没发出去的总的商品数量，及这次出入库存的商品数
	select #pdtTemp1.goodsid,isnull(stockout,0)as stockout,amount,#pdtTemp1.productspecs into #pdtTemp3 from #pdtTemp1 left join #pdtTemp2 on #pdtTemp1.goodsid=#pdtTemp2.goodsid

	--批量插入商品出库纪录
	insert storage(productno,amount,warehousing,leave,memberid,times,remark,goodsid,specs)
	select goodsno,amount,@flag,storage+stockout,@adminid,getDate(),@remarks,#pdtTemp3.goodsid,isnull(productspecs,'') from #pdtTemp3,goods(nolock)
	where #pdtTemp3.goodsid=goods.goodsid

	end
	------------------------------------------------------------------------------------------------------------------------
	--管理后台添加入库记录
	else
	begin
	select a.value as 'goodsID',b.value as 'amount',c.value as 'remark' into #pdttemp4
	from
	(select *from dbo.SplitToTable_Func(@goodsIDs,','))a,
	(select *from dbo.SplitToTable_Func(@amounts,','))b,
	(select *from dbo.SplitToTable_Func(@remarks,','))c
	where a.id=b.id and b.id=c.id

	--#pdtTemp5 orderproduct表中 商品ID及对应在orderproduct中还没发出去的总商品数量
	select op.goodsid ,sum(stockout)as stockout into #pdtTemp5 from orderproduct op,#pdtTemp4 #p4 where stockout >0 
	and op.goodsid=#p4.goodsid group by op.goodsid
	--#pdtTemp6 包含商品ID及对应在orderproduct中还没发出去的总的商品数量，及这次出入库存的商品数
	select #pdtTemp4.goodsid,isnull(stockout,0)as stockout,amount,remark into #pdtTemp6 from #pdtTemp4 left join #pdtTemp5 on #pdtTemp4.goodsid=#pdtTemp5.goodsid
	
--	--更新goods表中的库存数
--	update goods set storage=storage+amount from goods g,#pdttemp4 #p4 where g.goodsid=#p4.goodsid
	exec XpProc_ProductStorage_Update null,@goodsIDs,@amounts,1
	
	--批量插入商品入库纪录
	insert storage(productno,amount,warehousing,leave,memberid,times,remark,goodsid,specs)
	select goodsno,amount,@flag,storage+stockout,@adminid,getDate(),remark,#pdtTemp6.goodsid,isnull(PropsDesc,'') from #pdtTemp6,goods(nolock)
	where #pdtTemp6.goodsid=goods.goodsid

	--批量插入系统EventLog日志
	declare @RootCatID int,@SubCatID int
	set @RootCatID=5
	set @SubCatID=55
	INSERT eventlog(MemberID,MemberName,RealName,RootCatID,SubCatID,Description,IP)
	select @adminid,COALESCE(@adminName,''),COALESCE(@RealName,''),COALESCE(@RootCatID,0),COALESCE(@SubCatID,0),'商品入库:货品名称('+goodsName+')  入库数量('+amount+')',COALESCE(@IP,('0.0.0.0'))
    from goods g,#pdttemp4 #p4
	where g.goodsid=#p4.goodsid
	set @errorFlag=0
	end
end

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_StorageCheck_Add]    脚本日期: 04/09/2012 18:29:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-10-09>
-- Description:	<管理后台,盘点库存>
-- Debug:
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_StorageCheck_Add]
@productids varchar(8000)=null,--商品ID格式为'1,2,3'
@goodsids varchar(8000)=null,--货品ID 格式为'1,2,3'
@warehousings varchar(8000)=null,--盘点方式 1为增加，-1为减少
@amounts varchar(8000)=null,--盘点数量 格式为'1,2,3'
@remarks varchar(8000)=null,--盘点说明 格式为'盘点1,盘点2,盘点3'
@issue varchar(20)=null,--盘点期数
@adminid int ,--管理员ID
--以下的系统日志用到
@adminname varchar(20)=null,--管理员账号
@realname varchar(20)=null,--管理员真实姓名
@ip varchar(40)=null,--管理员ip
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
set nocount on
Begin Try
select a.value as 'goodsID',b.value as 'warehousing',c.value as 'amount',d.value as 'remark' into #temp1
from
(select *from dbo.SplitToTable_Func(@goodsids,','))a,
(select *from dbo.SplitToTable_Func(@warehousings,','))b,
(select *from dbo.SplitToTable_Func(@amounts,','))c,
(select *from dbo.SplitToTable_Func(@remarks,','))d
where a.id=b.id and b.id=c.id and c.id=d.id

begin tran
--插入盘点记录
INSERT INTO StorageCheck (ProductNo,Amount,Warehousing,Leave,MemberID,Times,Remark,Issue,GoodsID,Specs) 
select goodsno,amount,warehousing ,case warehousing when '1' then storage+amount when '-1' then storage-amount end,@adminid,getDate(),remark,@issue,t.goodsid,isnull(propsdesc,'') from goods g,#temp1 t
where g.goodsid=t.goodsid


--更新商品的库存量,跟盘点库存共用一个存储过程
exec XpProc_ProductStorage_Update @productids,@goodsids,@amounts,@warehousings

--批量插入系统EventLog日志
declare @RootCatID int,@SubCatID int
set @RootCatID=5
set @SubCatID=57
INSERT eventlog(
MemberID,MemberName,RealName,RootCatID,SubCatID,Description,IP)
select @adminid,COALESCE(@adminName,''),COALESCE(@RealName,''),COALESCE(@RootCatID,0),COALESCE(@SubCatID,0),
case warehousing when '1' then '盘点库存:货品名称('+goodsName+')  增加数量('+amount+')' when '-1' then '盘点库存:货品名称('+goodsName+')  减少数量('+amount+')' end
,COALESCE(@IP,('0.0.0.0'))
from goods g,#temp1 t
where g.goodsid=t.goodsid

select @errorflag=0
select @errormsg='盘点完成'
commit tran
End Try

Begin Catch
-- 捕捉错误
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
rollback tran
End Catch
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_StoreCart_Look]    脚本日期: 04/09/2012 18:29:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Hakkas>
-- Create date: <2010-03-12>
-- Description:	<查看商家购物车信息>
/*
引用该存储过程的存储过程：
1、XpProc_Checkout_Init
*/

/*
modify history:  
version:v1.1   
author:hakkas@qq.com                                
time:20110725                              
content:                                
1.添加输出参数@banknum记录购物车是否包含银行促销商品                                
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_StoreCart_Look] 
@cartid nvarchar(50),--购物车ID
@memberid int=-1,--会员ID
@sid int =0,--商品所属商家ID
@pdtPrice money out,--商品金额
@weight decimal(18,2) out,--商品重量
@banknum int out--银行活动商品数量
AS
BEGIN
--declare @pdtprice money,@weight decimal(18,2)
--exec XpProc_StoreCart_Look 'bed4026f-684b-4056-8843-0111c090b7bd',2,0,@pdtprice out,@weight out
--select @pdtprice,@weight
declare @scorerate decimal(18,2)--积分兑换货币比率
select @scorerate=0.01

--获取会员对应会员组享受的折扣
declare @groupid int,--会员组ID
@groupname nvarchar(20),--会员组名称
@discount decimal(18,2)--会员组折扣
select @groupid=groupid,@groupname=mg.groupname,@discount=cast(mg.discount/100.00 as decimal(18,2)) from member m,membergroup mg where m.groupid=mg.MemberGroupID and m.memberid=@memberid
--print('获取会员对应会员组享受的折扣')
--select @groupid as '会员组ID',@discount as '会员组折扣'


--declare @cartid nvarchar(100)
--select @cartid='10a2fd6e-e9c4-4142-a9d8-41cf9c763f6c'


--1.购物车信息
select       
p.productid,p.productno,isnull(gg.goodsname,p.productname) as productname,gg.marketprice,gg.memberprice,gg.weight,      
c.CartID,c.quantity,
gg.weight*c.quantity subweight,      
isnull(g.pmtprice,gg.memberprice) as pmtprice,
--isnull(g.pmtprice,case when @discount<>'100' and p.IsDiscount=1 then gg.memberprice*cast(@discount/100.00 as decimal(18,2)) else null end) pmtprice,--优惠单价
isnull(g.pmtprice,gg.memberprice)*c.quantity SubMoney,--小计金额      
(gg.memberprice-isnull(g.pmtprice,gg.memberprice))*c.quantity LessMoney,--优惠金额      
 g.pmtname,g.RuleID ,g.RuleName,g.BasicType,g.SubType,      
convert(varchar(200),'') remark , 
gg.GoodsID,p.IsDiscount,1 IsDlvUnit,1 DlvUnit,MiniBuyNum,gg.Score,0 usescore,0 StowageID,1 IsOfferInvoice, 
RecordID,ProductSpecs  
,g.pmtid--活动ID
,p.supplierid,g.bankno
into #cart      
from
ShoppingCart c(nolock),goods gg(nolock),product p(nolock)     
left join PmtGoodsList g
on( p.productid=g.productid and g.BasicType='goods' and g.SubType in('discount','specialprice','limittime')--一个商品只能作一个特价或折扣
and charindex(','+convert(nvarchar(10),@groupid)+',',','+g.GroupIDs+',')>0--允许参与优惠活动的会员组才可以享受优惠
)       
where
--c.supplierid=@sid--目前购物车表的supplierid都是0，有问题
p.supplierid=@sid --只查看对应商家的购物车商品
and c.productid=p.productid
and gg.goodsid=c.goodsid--增加多维规格功能  
and p.productid=gg.productid      
and c.quantity>0
and c.ptype=1--商品      
and c.cartid=@cartid

update #cart set pmtprice=memberprice*@discount,submoney=submoney*@discount,lessmoney=(memberprice-memberprice*@discount)*quantity,rulename=@groupname+':'+left(convert(varchar(10),@discount*10),3)+'折' where isnull(pmtid,0)=0 and IsDiscount=1 and @discount<>'100'
--2.商品购买数量控制 
select b.*      
into #MemberBookProduct      
from MemberBookPmtGoods b(nolock),#cart c(nolock)      
where 
b.RuleID=c.RuleID and c.productid=b.productid 

--2.1购买总数量限制      
select p.RuleID,p.productid,g.PmtNumber maxgoodsnumber,sum(p.quantity) goodsnumber      
into #MemberBookProduct_a--购买总数统计表      
from #MemberBookProduct p(nolock),PmtGoods g(nolock)      
where g.ruleid=p.ruleid      
and g.productid=p.productid      
and g.PmtNumber>0--限制数量
group by p.RuleID,p.productid,g.PmtNumber      
having sum(p.quantity)>=g.PmtNumber      
      
--2.2会员购买数量限制      
select p.ruleid,p.productid,memberid ,g.LimitedNumber maxmembernumber,sum(quantity) membernumber      
into #MemberBookProduct_b--个人购买统计表      
from #MemberBookProduct p(nolock) ,PmtGoods g(nolock)      
where       
g.ruleid=p.ruleid      
and g.productid=p.productid      
and g.LimitedNumber>0--限制数量      
and memberid=@memberid      
group by  p.ruleid,p.productid,memberid ,g.LimitedNumber        
having sum(p.quantity)>=g.LimitedNumber      
      
--2.3汇总      
--2.3.1      
update c set c.quantity=0,SubMoney=0,LessMoney=0, remark='此商品已经抢购完,<span style="color:Green;">谢谢您的支持，请在下次购买</span>'                
from #cart c,#MemberBookProduct_a a(nolock)                            
where                     
c.ruleid=a.ruleid                            
and c.productid=a.productid      
      
--2.3.2      
update c set c.quantity=0,SubMoney=0,LessMoney=0, remark='您已超过此商品最大购买抢购量:'+convert(varchar(8),a.maxmembernumber)+',<span style="color:Green;">谢谢您的支持，请在下次购买</span>'              
from #cart c,#MemberBookProduct_b a(nolock)                            
where                            
c.ruleid=a.ruleid                            
and c.productid=a.productid         
      
--2.3.3     
update c set c.quantity=0,SubMoney=0,LessMoney=0, remark='您已超过此商品最大购买抢购量:'+convert(varchar(8),a.LimitedNumber)+',<span style="color:Green;">请修改数量</span>'              
from #cart c,PmtGoods a(nolock)                            
where                            
c.ruleid=a.ruleid                            
and c.productid=a.productid                            
and ((c.quantity> a.PmtNumber and  a.PmtNumber>0)                             
or c.quantity>a.LimitedNumber and a.LimitedNumber>0) 
    

--3.1购物车汇总，获取参与促销活动汇总信息                        
--drop table  #orderinfo                 
select l.ruleid,sum(SubMoney) totalprice,sum(quantity) totalnumber                            
into #orderinfo                            
from #cart c(nolock),PmtGoodsList l(nolock)                            
where                         
1=1                        
and                         
c.productid=l.productid        
and c.goodsid=l.goodsid                      
and l.SubType='gift'   --礼品换购信息                          
group by l.ruleid    
                          
--3.2获取赠品商品信息                        
if object_id('tempdb.dbo.#gift') is not null                            
begin       
drop table #gift                            
end                                
select  floor(                        
case when isautoAdded=1 then                            
case when r.BasicType='orders' then o.totalprice                            
when r.BasicType='goods' then o.totalnumber end/minvalue  --订单满额规格可能有问题
else 1 end) giftnumber,--可获礼品数量                            
convert(varchar(200),' ') giftremark, r.BasicType,g.SubType,                       
g.ID,g.PmtName,g.RuleID,g.RuleNo,                        
g.RuleName,g.productid,g.goodsid,g.productname,                        
g.categoryid,g.brandid,g.brandname,g.usescore,g.score,                        
g.marketprice,g.memberprice,g.PmtPrice,g.stowageid,                        
g.PmtNumber,g.LimitedNumber,g.IsLimited,g.maxnumber,g.isselected,                        
g.gifttype,g.groupname,g.addtime,g.status,                        
--g.adduser,g.deltime,g.deluser,
g.remark,
r.PmtID,g.supplierid                     
into #gift                             
from #orderinfo o(nolock),PmtRule r(nolock),PmtGifts g(nolock),Product p(nolock)   -----------------------------这里为什么要联商品表product????????????                         
where                             
o.ruleid=r.ruleid                          
and p.productid=g.productid                          
and g.ruleid=r.ruleid                            
and r.SubType='gift'                            
and minvalue                            
<=case when r.BasicType='orders' then o.totalprice               
when r.BasicType='goods' then o.totalnumber end--起始条件                            
and (  maxvalue=0 or  isautoAdded=1 or                          
convert(money,maxvalue)>case when r.BasicType='orders' then o.totalprice                            
when r.BasicType='goods' then o.totalnumber end--最大条件                            
)

--4.礼品数量限制                    
if object_id('tempdb.dbo.#MemberBookGift') is not null                            
begin                            
drop table #MemberBookGift                            
end                            
select b.*                            
into #MemberBookGift                            
from MemberBookPmtGoods b(nolock),#gift c(nolock)                            
where b.RuleID=c.RuleID                            
and c.productid=b.productid                            
                            
--4.1总数限制                           
if object_id('tempdb.dbo.#MemberBookGift_a') is not null                            
begin                            
drop table #MemberBookGift_a                            
end           
select p.RuleID,p.productid,l.PmtNumber,sum(p.quantity) SaleNumber                            
into #MemberBookGift_a                            
from #MemberBookGift p(nolock),PmtGifts l(nolock)                            
where l.RuleID=p.RuleID                            
and l.productid=p.productid                            
and l.PmtNumber>0--有限制数量                            
group by p.RuleID,p.productid,l.PmtNumber                            
having sum(p.quantity)>=l.PmtNumber                      
                            
--4.2个人数量限制                           
if object_id('tempdb.dbo.#MemberBookGift_b') is not null                            
begin                            
drop table #MemberBookGift_b                            
end                            
select p.RuleID,p.productid,memberid,l.LimitedNumber,sum(quantity) PersonalNumber                            
into #MemberBookGift_b                            
from #MemberBookGift p(nolock) ,PmtGifts l(nolock)                            
where                             
l.RuleID=p.RuleID                            
and l.productid=p.productid                            
and l.LimitedNumber>0--有限制个人购买数量                            
and memberid=@memberid                            
group by  p.RuleID,p.productid,memberid,l.LimitedNumber                              
having sum(p.quantity)>=l.LimitedNumber 
                           
--4.3 赠品信息汇总 
--4.3.1 赠品信息,此礼品已经送完完                          
update c set giftnumber=0,giftremark='此礼品已经送完'                            
from #gift c,#MemberBookGift_a a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                        
--4.3.2 赠品信息,你已超过此礼品的最大量                        
update c set giftnumber=0,giftremark='你已超过此礼品的最大量!'                            
from #gift c,#MemberBookGift_b a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                            
--4.3.3 赠品信息,最后一次仍送出                          
update c set giftnumber=a.LimitedNumber,giftremark='最后一次仍送出!'                            
from #gift c,PmtGoods a(nolock)                            
where                            
c.RuleID=a.RuleID                            
and c.productid=a.productid                            
and ((c.giftnumber> a.PmtNumber and  a.PmtNumber>0)                             
or c.giftnumber>a.LimitedNumber and a.LimitedNumber>0) 

--4.4 赠品库存控制    
update c set giftnumber=0,giftremark='很抱歉，此赠品已经送完!'                            
from #gift c,goods g(nolock)                            
where            
c.goodsid=g.goodsid    
and g.Storage<=0

--5 订单总金额优惠信息                          
select top 0  TotalMoney=0, LessMoney=0,ruleid=' ' ,rulename=' ' ,moneyremark=' '                           
into #orderpromotion

--6 显示信息

--6.1 商品购物车表                            
delete from goodscart where cartid=@cartid                                                     
insert into goodscart(                     
cartid,productid,productno,marketprice,memberprice,weight,                            
pmtprice,quantity,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,remark,                        
GoodsID, IsDlvUnit, DlvUnit,MiniBuyNum,Score,                        
StowageID,IsOfferInvoice,RecordID,ProductSpecs                      
,pmtid,IsDiscount,UseScore,ScoreMoney,SupplierID                          
)                            
select @cartid,productid,productno,marketprice,memberprice,weight,                            
pmtprice,quantity,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,remark,                        
GoodsID, IsDlvUnit, DlvUnit,MiniBuyNum,Score*quantity,                        
StowageID,IsOfferInvoice,RecordID,ProductSpecs                        
,pmtid,IsDiscount,UseScore,UseScore*@scorerate,SupplierID                              
from  #cart c(nolock)

--6.2礼品购物车表 
--description:统计原先换购的礼品和积分兑换的礼品放入#oldgift，清空礼品购物车中非换购和积分兑换的礼品，

--6.2.1保证原先选择的礼品不会被删除                        
select  c.*                         
into  #oldgift                        
from giftscart c(nolock),#gift t(nolock)                         
where                         
(isnull(c.ruleid,0)=0 and c.UseScore>0 and c.cartid=@cartid)--积分兑换的礼品                        
or
(c.addtime>getdate()-1                        
and c.productid=t.productid                         
and c.giftnumber=t.giftnumber                        
and c.giftnumber>0--礼品数量为0的不能保留                        
and c.isSystemAdd=0--礼品非系统自动添加                        
and c.cartid=@cartid)
                         
-- 商品数量进行了修改，需要删除变化礼品信息                    
delete g                         
from giftscart g(nolock)                        
where                         
1=1                        
and g.RuleID not in(            
select o.ruleid                          
from  #oldgift o(nolock) 
where cartid=@cartid                        
)                                                
and g.cartid=@cartid  

--6.2.2 单个礼品规则，且价格为0的，自动添加到礼品表中。                        
--选出规则中只有单个礼品，且价格为0的规则,且上次保留的礼品信息                      
select g.ruleid                        
into #SinpleGift                        
from #gift g                         
where                         
1=1                         
and g.ruleid not in(                         
select o.ruleid                         
from  #oldgift o(nolock) where cartid=@cartid                        
)  
--and g.giftnumber>0                      
and g.pmtprice=0                        
group by g.ruleid                        
having count(g.ruleid)=1

--6.2.3 系统自动添加的礼品信息                                     
insert into giftscart(                            
cartid,productid,productno,marketprice,memberprice,weight                            
,pmtprice,giftnumber,subweight,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,giftremark                         
,productname,isSystemAdd,pmtid,UseScore,supplierid,goodsid,rulename,ImgFolder,ProductImg                          
)                            
select @cartid,c.productid,p.productno,c.marketprice,c.memberprice,p.weight                           
,c.pmtprice,giftnumber,giftnumber*p.weight,c.pmtprice*giftnumber submoney,(c.memberprice-c.pmtprice)*giftnumber lessmoney, --有疑惑                          
pmtname,c.ruleid,basictype,subtype,giftremark                        
,p.productname ,1 isSystemAdd,c.pmtid,0,--非积分兑换，使用积分为0 
c.supplierid,c.goodsid,c.rulename,p.imgfolder,p.productimg                             
from  #gift c(nolock) ,#SinpleGift s(nolock),product p(nolock)                        
where 
c.ruleid=s.ruleid and c.productid=p.productid                     

--积分兑换的礼品
insert into giftscart(                            
cartid,productid,productno,marketprice,memberprice,weight                           
,pmtprice,giftnumber,subweight,submoney,lessmoney,giftremark                         
,productname,isSystemAdd,UseScore,supplierid,goodsid,ImgFolder,ProductImg                         
)
select @cartid,s.productid,p.productno,p.marketprice,p.memberprice,p.weight                           
,0 pmtprice,s.quantity,s.quantity*p.weight,0 submoney,p.memberprice*s.quantity lessmoney,'积分兑换' giftremark                        
,p.productname ,0 isSystemAdd,s.giftscore,p.supplierid,s.goodsid,p.imgfolder,p.productimg                               
from  shoppingcart s(nolock),product p(nolock)                       
where 
s.cartid=@cartid and s.ptype=2 and s.productid=p.productid

--6.2.4 删除系统自动添加的礼品信息                       
delete c                        
from  #gift c(nolock) ,#SinpleGift s(nolock)                        
where c.ruleid=s.ruleid   

--6.2.5 可选礼品信息表                       
delete from GiftsCart_temp where cartid=@cartid                        
insert into GiftsCart_temp(                            
cartid,productid,productno,marketprice,memberprice                            
,pmtprice,giftnumber,submoney,lessmoney,                            
pmtname,ruleid,basictype,subtype,giftremark,productname                  
)                         
select @cartid,p.productid,p.productno,c.marketprice,c.memberprice                            
,pmtprice,c.giftnumber,c.memberprice*giftnumber submoney,c.pmtprice*giftnumber lessmoney,                            
c.pmtname,c.ruleid,basictype,subtype,giftremark,p.productname              
from  #gift c(nolock),product p(nolock)                        
where c.productid=p.productid

                           
                     
--7 购物车信息                        
--7.1显示购物车商品信息      
print('output->7.1显示购物车商品信息  ')                          
select '' as 购物车商品信息,
* from                             
#cart c(nolock)

--统计银行促销商品数量,实际应用时根据bankno来识别不同银行的活动商品
--bankno 1:中国银行;2:工商银行;3:建设银行;4:农业银行;5:招商银行;6:交通银行;7:光大银行
select @banknum=count(1) from #cart c(nolock) where c.bankno='5'
                           
--7.2显示购物车礼品信息
print('output->7.2显示购物车礼品信息')                                                      
select '' as 购物车礼品信息,
c.*,c.giftnumber*usescore as UsedTotalScore                   
from giftscart c(nolock)                
where cartid=@cartid and supplierid=@sid                   
                       
/*
--7.3需要用户自己选择的礼品，需要会员自己决定手工将礼品加入到礼品表中 
if coalesce(@memberid, -1)=-1                         
begin  
--未登录会员不显示礼品信息 
print('output->7.3未登录会员不显示可选择礼品信息')                                             
select top 0 c.* ,r.rulename from giftscart_temp c,pmtrule r(nolock) where cartid=@cartid and c.ruleid = r.ruleid                                             
end
                            
else                             
begin 
--已登录会员显示礼品信息 
print('output->7.3已登录会员显示可选择礼品信息')                   
select '' as 可选礼品信息,
c.* ,r.rulename from giftscart_temp c,pmtrule r(nolock) where cartid=@cartid and c.ruleid = r.ruleid                                      
end
*/

--7.4订单信息 
--订单商品品种数、商品总数量、总金额、总积分、总优惠的金额 
print('output->7.4订单商品品种数、商品总数量、总金额、总获得积分、总使用积分、总的积分抵扣金额、总优惠的金额')
select cartid,count(productid) goodsnumber,sum(quantity) totalnumber ,sum(subweight) totalweight,sum(submoney-scoremoney) totalmoney ,sum(score) totalscore,sum(usescore) usedscore,sum(scoremoney) totalscoremoney,sum(LessMoney) totallessmoney                        
into #ordermessage                  
from                        
(                        
select cartid,productid,goodsid,quantity,subweight,submoney,Score,UseScore,ScoreMoney,LessMoney,supplierid                         
from goodscart g(nolock)                        
where cartid=@cartid and supplierid=@sid                       
union                        
select cartid,productid,goodsid,giftnumber,subweight,submoney, 0 Score,UseScore,0 ScoreMoney,LessMoney,supplierid                         
from giftscart g(nolock)                        
where cartid=@cartid and supplierid=@sid                       
) as t                        
group by cartid
select @pdtPrice=totalmoney,@weight=totalweight from #ordermessage
select * from #ordermessage

--7.5订单金额优惠信息,暂时不做                                        
print('output->7.5订单金额优惠信息,暂时不做')                            
select top 1 '订单优惠金额暂时先不做' as 订单优惠金额暂时先不做,
* from #orderpromotion


/*
print('debug->商品购物车') 
select '商品购物车' as debug商品购物车,
* from goodscart
print('debug->礼品购物车')                           
select '礼品购物车' as debug礼品购物车,
* from giftscart                    
*/
                     
--declare @shipfeer money,@CouponValue money,
--declare @ordermoney money                      
--select @shipfeer=0                  
--select @CouponValue=0                      
--select @ordermoney=(select top 1 totalmoney from #ordermessage)                      
                      
/*
print('--10.5运费  ')                                            
delete from ShipCart where cartid=@cartid                      
insert into ShipCart(cartid,shipfeer,memberid)                       
values(@cartid,@shipfeer,@memberid)                      
                    
select shipfeer=@shipfeer                      
print('--10.6优惠券')                      
select   CouponValue ,CouponName                      
into #CouponCart                      
from CouponCart c(nolock),CouponDetail d(nolock)                      
where c.CartID=@CartID                      
and d.CouponID=c.CouponID                   
and c.CouponID in (select CouponID from goodscart(nolock) where cartid=@cartid)                    
select * from #CouponCart                      
select @CouponValue=(select  isnull(sum(CouponValue),0)  from #CouponCart)                      
*/
              
--print('output->应付款')                      
--select neepaymoney=@ordermoney+@shipfeer-@CouponValue                      
--select neepaymoney=@ordermoney 

/*                   
print('10.8参与活动或者是其它信息')                     
if object_id('tempdb.dbo.#activelist_temp') is not null                    
begin                    
drop table #activelist_temp                    
end                    
create table #activelist_temp                    
(                    
activename varchar(1000) default '',                    
tipmessage varchar(200) default ''                    
)                    
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;">满50元可使用5元优惠券（促销商品除外）</span>',tipmessage='满50元可使用5元优惠券'                     
                    
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;">满100元可使用10元优惠券（促销商品除外）</span>',tipmessage='满100元可使用10元优惠券'                     
                
                
insert into #activelist_temp                     
select top 1 activename='<span style="color:red;cursor:pointer;"><a href="products/product-1100530.html">5L金龙鱼花生浓香调和油特价每人限购1瓶</a></span>',tipmessage='5L金龙鱼花生浓香调和油特价每人限购1瓶,数量有限'      
where getdate() between getdate()-5 and  '2010-12-01'                 
                
select  *  from #activelist_temp  
*/

END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SubCategory_Delete]    脚本日期: 04/09/2012 18:29:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

----------------------------------------------------------------------------
-- Delete a single record from SubCategory
----------------------------------------------------------------------------
CREATE PROC [dbo].[XpProc_SubCategory_Delete](
	@cid varchar(20),
	@sid int
)
AS
if Exists(select cid from subcategory where cid=@cid and sid=@sid)
begin
declare @parentid varchar(20)
--记录分类的父级ID，以便更新父级分类的子类数量
select @parentid=parentid from subcategory where cid=@cid and sid=@sid
DELETE SubCategory WHERE cid=@cid and sid=@sid
update subcategory set childs=childs-1 where cid=@parentid and sid=@sid
end






GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SubCategory_Insert]    脚本日期: 04/09/2012 18:29:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

----------------------------------------------------------------------------
-- Insert a single record into SubCategory
----------------------------------------------------------------------------
CREATE PROC [dbo].[XpProc_SubCategory_Insert]
	@cname varchar(50),
	@logo varchar(200) = NULL,
	@parentid varchar(20),
	@catad varchar(200)=NULL ,
	@pagesize int = NULL,
	@sort int = NULL,
	@stype tinyint = NULL,
	@status int = NULL,
	@sid int = NULL
AS
declare @cid varchar(20),@pdtnum int,@tempcid int,@depth int,@step int
select @step=2--分类步长为2
/*
select @tempcid=cast((rand()*(100-1)+1) as int)
while Exists(select cid from subcategory where cid=@cid and sid=@sid)
begin 
select @tempcid=cast((rand()*(100-1)+1) as int)
end
select @cid=cast(@tempcid as varchar(2))
*/
--获取层级
select @depth=len(@parentid)/@step+1

--获取分类ID
select ROW_NUMBER() OVER (ORDER BY cid asc, addtime asc) AS ROWID,cid into #c from subcategory(nolock) where parentid=@parentid and sid=@sid
select @cid=max(rowid)+1 from #c
select @cid=isnull(@cid,1)

--如果未指定排序号，则使用数据库的序号作为排序号
if @sort=-1
select @sort=@cid

select top 1 @cid=isnull(rowid,@cid) from #c where rowid<>right(cid,2)
select @cid='1000'+@cid
select @cid=right(@cid,2)
if @depth=2
select @cid=@parentid+@cid

INSERT SubCategory(
cid, cname, logo, parentid, depth, catad, childs, pdtnum, pagesize, sort, stype, status, sid)
VALUES(
@cid, @cname, @logo, @parentid, @depth, COALESCE(@catad,''), 0, COALESCE(@pdtnum, (0)), @pagesize, @sort, COALESCE(@stype, (0)), COALESCE(@status, (1)), COALESCE(@sid, (0)))

--更新父类的子分类数目
--update subcategory set childs=childs+1 where cid=parentid
update subcategory set childs=childs+1 where cid=@parentid and sid=@sid
--if object_id('tempdb..#c') is not null
--Begin
--    drop table #c
--End 







GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SubCategory_Select]    脚本日期: 04/09/2012 18:29:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
/*
function:获取商家店内分类                               
careatetime:20110328                               
author:hakkas 
*/
CREATE PROC [dbo].[XpProc_SubCategory_Select]
	@sid int--供应商的ID
AS
begin
select * into #ssc from subcategory where sid=@sid
select s1.*,isnull(s2.sort,s1.sort) as ssort,left(s1.cid,2) as cno from #ssc s1 left join #ssc s2 on s1.parentid=s2.cid order by ssort,cno,depth,sort,cid
end


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SubCategory_Update]    脚本日期: 04/09/2012 18:29:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------------------------------------------------------------------
-- Update a single record in SubCategory
----------------------------------------------------------------------------
CREATE PROC [dbo].[XpProc_SubCategory_Update]
	@cid varchar(20),
	@cname varchar(50),
	@logo varchar(200) = NULL,
	@parentid varchar(20),
	@depth int,
	@catad varchar(200) = NULL,
	@childs int,
	@pdtnum int,
	@pagesize int = NULL,
	@sort int = NULL,
	@stype tinyint,
	@status int,
	@sid int
AS

UPDATE	SubCategory
SET	cname = @cname,
	logo = @logo,
	parentid = @parentid,
	depth = @depth,
	catad = @catad,
	childs = COALESCE(@childs, (0)),
	pdtnum = COALESCE(@pdtnum, (0)),
	pagesize = @pagesize,
	sort = @sort,
	stype = COALESCE(@stype, (0)),
	status = COALESCE(@status, (1)),
	sid = COALESCE(@sid, (0))
WHERE 	cid = @cid


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SubCategoryChilds_Update]    脚本日期: 04/09/2012 18:29:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas>
-- Create date: <2011-10-10>
-- Description:	<更新店铺分类的子分类数目>
-- =============================================
create PROCEDURE [dbo].[XpProc_SubCategoryChilds_Update]
AS
BEGIN
select parentid,count(1) as childs ,sid
into #c 
from subcategory group by parentid,sid

update s set s.childs=isnull(c.childs,0) 
from subcategory s 
left join #c c on s.cid=c.parentid and s.sid=c.sid 
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Suit_Add]    脚本日期: 04/09/2012 18:29:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-08-28>
-- Description:	<添加套装>
/*debug
declare @errorflag int,@errormsg varchar(200)
exec XpProc_Suit_Add '电脑套装测试',5,'2011-8-30','2011-9-10','3552,3672,3766,3731,3713','3532,3652,3746,3711,3693','2540,1605,60,167,116','1,1,1,1,1','1,2,3,4,5','1,0,0,0,0','0,0,0,0,0','测试套装',2,'admin',0,@errorflag out,@errormsg out
select @errorflag,@errormsg
*/
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Suit_Add]
@suitname varchar(100),--套装名称
@stock int,--数量
@begintime datetime,--开始时间
@endtime datetime,--结束时间
@pids varchar(1000),--商品ID连接字符串
@gids varchar(1000),--货品ID连接字符串
@prices varchar(1000),--价格连接字符串
@nums varchar(1000),--数量连接字符串
@sorts varchar(1000),--排序连接字符串
@ms varchar(1000),--是否主商品连接字符串
@scores varchar(1000),--积分连接字符串
@remark varchar(200),--备注
@adduser int,--添加人会员ID
@addusername varchar(50),--添加人账号
@supplierid int,--商家ID
@errorFlag int output,--错误标志
@errorMsg varchar(200)output --错误信息
AS
BEGIN
--insert log(content)values(@suitname+': '+cast(@stock as varchar(10))+': '+cast(@begintime as varchar(102))+': '+cast(@endtime as varchar(100))+': '+@pids+': '
--+@gids+': '+@prices+': '+@nums+': '+@sorts+': '+@ms+': '+@scores+': '+@remark)

Begin Try
begin tran
select * into #t1 from SplitToTable_Func(@pids,',')
select * into #t2 from SplitToTable_Func(@gids,',')
select * into #t3 from SplitToTable_Func(@prices,',')
select * into #t4 from SplitToTable_Func(@nums,',')
select * into #t5 from SplitToTable_Func(@sorts,',')
select * into #t6 from SplitToTable_Func(@ms,',')
select * into #t7 from SplitToTable_Func(@scores,',')
--insert into log(content)values(@scores)

select 0 as suitid,t1.value as productid, t2.value as goodsid,g.memberprice as oldprice,convert(decimal(18,2),t3.value) as price,t4.value as quantity,case when t6.value='1' then '1' else t5.value end as sort,t6.value as ismaster,convert(int,t7.value) as score
into #t
from #t1 t1,#t2 t2,#t3 t3,#t4 t4,#t5 t5,#t6 t6,#t7 t7,goods g(nolock)
where t1.id=t2.id and t1.id=t3.id and t1.id=t4.id and t1.id=t5.id and t1.id=t6.id and t1.id=t7.id and t2.value=g.goodsid
select * from #t
declare @suitid int,@mainpdtid int,@maingoodsid int,@oldprice decimal(18,2),@price decimal(18,2),@score int
select @mainpdtid=productid,@maingoodsid=goodsid from #t where ismaster=1
select @oldprice=sum(oldprice),@price=sum(price),@score=sum(score) from #t

-- 插入套装主体信息
INSERT suit(SuitName, MainPdtID, MainGoodsID, OldPrice, Price, Score, Stock, Balance, Remark, BeginTime, EndTime,AddUser, AddUserName,SupplierID)
VALUES (@SuitName, @mainpdtid, @maingoodsid, @oldprice, @price, COALESCE(@score, (0)), @Stock, @Stock, @Remark, @BeginTime, @EndTime, @AddUser, @AddUserName,@SupplierID)

--获取刚添加的套装ID
select @suitid=@@IDENTITY

--更改临时表中的套装ID
update #t set suitid=@suitid
--插入套装明细
insert into suitdetail(suitid,productid,goodsid,oldprice,price,quantity,sort,ismaster,score)
select * from #t order by ismaster desc,sort asc

select @errorflag=0,@errormsg=''
commit tran
End Try

Begin Catch
rollback tran
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return 0
End Catch
END


--DECLARE	@return_value int,
--		@errorFlag int,
--		@errorMsg varchar(200)
--
--EXEC	@return_value = [dbo].[XpProc_Suit_Add]
--		@suitname = N'套装商品',
--		@stock = 10,
--		@begintime = N'2011-09-03',
--		@endtime = N'2011-09-09',
--		@pids = N'1,2',
--		@gids = N'1,2',
--		@prices = N'10,12',
--		@nums = N'2,3',
--		@sorts = N'1,2',
--		@ms = N'1,0',
--		@scores = N'10,12',
--		@remark = N'测试套装',
--		@adduser = 2,
--		@addusername = N'admin',
--		@supplierid = 0,
--		@errorFlag = @errorFlag OUTPUT,
--		@errorMsg = @errorMsg OUTPUT
--
--SELECT	@errorFlag as N'@errorFlag',
--		@errorMsg as N'@errorMsg'
--
--SELECT	'Return Value' = @return_value



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Suit_Delete]    脚本日期: 04/09/2012 18:29:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-08-28>
-- Description:	<删除套装>
-- =============================================
CREATE procedure [dbo].[XpProc_Suit_Delete]
--@suitid int,
@suitids varchar(1000),
@errorflag int out,--错误标志
@errormsg varchar(200) out--错误信息描述
AS
BEGIN
select @errorflag=0,@errormsg=''

Begin Try
begin tran
select * into #s from SplitToTable_Func(@suitids,',')
--删除套装购物车的套装
delete suitscart from suitscart(nolock) sc,#s where sc.suitid=#s.value

--删除购物车里的套装
--delete from shoppingcart where ptype=3 and productid=@suitid
delete shoppingcart from shoppingcart(nolock) sc,#s where  sc.ptype=3 and sc.productid=#s.value


--删除套装明细
--delete from suitdetail where suitid=@suitid
delete suitdetail from suitdetail(nolock)sd,#s where sd.suitid=#s.value

--删除套装主体信息
--delete from suit where suitid=@suitid
delete suit from suit(nolock) s,#s where s.suitid=#s.value
commit tran
End Try

Begin Catch
-- 捕捉错误
rollback tran
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END







GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Suit_Update]    脚本日期: 04/09/2012 18:29:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-08-28>
-- Description:	<更新套装>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Suit_Update]
@suitid int,--套装ID
@suitname varchar(100),--套装名称
@stock int,--数量
@begintime datetime,--开始时间
@endtime datetime,--结束时间
@pids varchar(1000),--商品ID连接字符串
@gids varchar(1000),--货品ID连接字符串
@prices varchar(1000),--价格连接字符串
@nums varchar(1000),--数量连接字符串
@sorts varchar(1000),--排序连接字符串
@ms varchar(1000),--是否主商品连接字符串
@scores varchar(1000),--积分连接字符串
@remark varchar(200),--备注
@updateuser int,--添加人会员ID
@updateusername varchar(50),--添加人账号
@errorFlag int output,--错误标志
@errorMsg varchar(200) output--错误信息
AS
BEGIN
Begin Try
begin tran
select * into #t1 from SplitToTable_Func(@pids,',')
select * into #t2 from SplitToTable_Func(@gids,',')
select * into #t3 from SplitToTable_Func(@prices,',')
select * into #t4 from SplitToTable_Func(@nums,',')
select * into #t5 from SplitToTable_Func(@sorts,',')
select * into #t6 from SplitToTable_Func(@ms,',')
select * into #t7 from SplitToTable_Func(@scores,',')

select suitid=@suitid,t1.value as productid, t2.value as goodsid,g.memberprice as oldprice,t3.value as price,t4.value as quantity,case when t6.value='1' then 1 else t5.value end as sort,t6.value as ismaster,isnull(t7.value,0) as score
into #t
from #t1 t1,#t2 t2,#t3 t3,#t4 t4,#t5 t5,#t6 t6,#t7 t7,goods g(nolock)
where t1.id=t2.id and t1.id=t3.id and t1.id=t4.id and t1.id=t5.id and t1.id=t6.id and t1.id=t7.id and t2.value=g.goodsid

declare @mainpdtid int,@maingoodsid int,@oldprice decimal(18,2),@price decimal(18,2),@score int
select @mainpdtid=productid,@maingoodsid=goodsid from #t where ismaster=1
select @oldprice=sum(cast(oldprice as decimal(18,2))),@price=sum(cast(price as decimal(18,2))),@score=sum(cast(score as int)) from #t

-- 更新套装主体信息
update suit
set SuitName=@SuitName, 
MainPdtID=@mainpdtid, 
MainGoodsID=@maingoodsid, 
OldPrice=@oldprice, 
Price=@price, 
Score=@score, 
Stock=@Stock,
Remark=@Remark, 
BeginTime=@BeginTime, 
EndTime=@EndTime,
UpdateUser=@UpdateUser, 
UpdateUserName=@UpdateUserName,
UpdateTime=getdate()
where suitid=@suitid

--删除旧的套装明细
delete from suitdetail where suitid=@suitid

--插入新的套装明细
insert into suitdetail(suitid,productid,goodsid,oldprice,price,quantity,sort,ismaster,score)
select * from #t order by ismaster desc,sort asc

select @errorflag=0,@errormsg='更新成功'
commit tran
End Try

Begin Catch
rollback tran
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
print @errormsg
Return 0
End Catch
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SuitList_Get]    脚本日期: 04/09/2012 18:29:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		liwenhai
-- Create date: <2011-09-01>
-- Description:	<分页方式获取套装列表>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_SuitList_Get]
@pageno int,
@pagesize int,
@totalCount int output
--,
--@errorFlag int output
AS
BEGIN
select *from(
select SuitID,SuitName,BeginTime,EndTime,Remark,Row_number() over(order by SuitID desc) as rowno from suit(nolock) )as suit 
where rowno>convert(varchar(50),@pagesize*(@pageno-1)) and rowno<=convert(varchar(50),@pagesize*@pageno)
select @totalCount=count(*)from suit(nolock)
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SuitRelatedInfo_Get]    脚本日期: 04/09/2012 18:29:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-08-28>
-- Description:	<获取套装相关信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_SuitRelatedInfo_Get]
@suitid int, --套装ID
@pids varchar(1000) output,--用逗号分隔的商品明细的productid
@gids varchar(1000) output--用逗号分隔的商品明细的goodsid
AS
BEGIN
--获取套装基本信息
select suitid,suitname,OldPrice, Price, Score, Stock,Remark, BeginTime, EndTime 
from suit(nolock) 
where suitid=@suitid

--获取套装的商品明细信息
select d.suitid,d.productid,d.goodsid,isnull(g.goodsname,p.productname)as goodsname,d.oldprice,d.price,d.quantity,d.sort,d.ismaster,d.score,p.imgfolder,p.productimg 
from suitdetail d(nolock),product p(nolock),goods g(nolock)
where d.productid=p.productid and d.goodsid=g.goodsid and d.suitid=@suitid

select @pids='',@gids=''
 
select @pids=@pids+','+cast(productid as varchar),@gids=@gids+','+cast(goodsid as varchar) 
from suitdetail(nolock) 
where suitid=@suitid

select @pids=stuff(@pids,1,1,'')
select @gids=stuff(@gids,1,1,'')
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Supplier_ShopAdmin_Delete]    脚本日期: 04/09/2012 18:29:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<根据SupplierID 更新二个表Supplier ShopAdmin>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Supplier_ShopAdmin_Delete](
	@SupplierID INT,
	@ErrorFlag int=1 output,
	@errormsg varchar(200)=null output
)
AS
--if exists(select Supplier.SupplierID,ShopAdmin.SupplierID from Supplier,ShopAdmin where Supplier.SupplierID=ShopAdmin.SupplierID and Supplier.SupplierID=@SupplierID)
--begin
--	declare @Error1 int,@Error2 int
--	begin Transaction
--	delete from	Supplier WHERE SupplierID = @SupplierID
--	set @Error1=@@Error
--	delete from	ShopAdmin WHERE SupplierID = '@SupplierID'
--	set @Error2=@@Error
--	if(@Error1<>0 or @Error2<>0)
--	begin
--		Rollback Transaction
--		set @ErrorFlag=-1
--	end
--	else
--	begin
--		Commit Transaction
--		set @ErrorFlag=0
--	end
--end
--else
--begin
--	set @ErrorFlag=-1
--end
set @ErrorFlag=1
begin
if @supplierid=0
begin
	select @errorflag=1
	select @errormsg='这个是系统默认商家不能删除！'
return
end
begin try
begin Transaction
delete from	Supplier WHERE SupplierID = @SupplierID
delete from	ShopAdmin WHERE SupplierID = @SupplierID
select @ErrorFlag=0
select @errormsg='删除成功！'
Commit Transaction
end try
Begin Catch
-- 捕捉错误
rollback
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
end
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Supplier_ShopAdmin_Insert]    脚本日期: 04/09/2012 18:29:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Supplier_ShopAdmin_Insert](
	@SupplierName nvarchar(50),
	@Logo nvarchar(50),
	@Description varchar(1000),
	@Address nvarchar(200),
	@Phone nvarchar(50),
	@Contacter nvarchar(50),
	@Remark nvarchar(200),
	@Banner varchar(200),
	@ContactInfo varchar(500),
	@Auditor int,
	@AuditorName varchar(50),
	@ExpireTime	datetime,
	@Password varchar(20),
	@BankName varchar(50),
	@BankAccount varchar(10),
	@BankNo varchar(30),
	@BankAddress varchar(50),
	@CategoryNo varchar(20),
	@BPRate float,
	@ErrorFlag int output,
	@errorMsg varchar(200) output,
	@supplierID int output
)
AS
BEGIN
	set @ErrorFlag=1
	set @errorMsg='添加商家失败！'
	begin try
	begin Transaction
    insert into supplier(SupplierName,Logo,Description,Address,Phone,Contacter,Remark,AddTime,Banner,ContactInfo,Template,PdtNum,Status,UpdateTime,AuditTime,Auditor,AuditorName,Shut,Password,ExpireTime,Reviews,pj1,pj2,pj3,pj4,pj5,Title,Keyword,Destn,BankName,BankAccount,BankNo,BankAddress,CategoryNo,BPRate)
	values (@SupplierName,@Logo,@Description,@Address,@Phone,@Contacter,@Remark,getDate(),@Banner,@ContactInfo,'',0,1,getDate(),getDate(),@Auditor,@AuditorName,1,'',@ExpireTime,1,0,0,0,0,0,'','','',@BankName,@BankAccount,@BankNo,@BankAddress,@CategoryNo,@BPRate)
	select @supplierID=@@identity 
	insert into ShopAdmin(username,password,flag,[power],supplierid,realname,phone,email,status,addtime)values(@@identity,@Password,3,'supplier',@@identity,@SupplierName,'','',1,getDate());
	set @ErrorFlag=0
	set @errorMsg='成功添加商家！'
	Commit Transaction
	end try 
	Begin Catch
	-- 捕捉错误
	select @errorflag=1
	select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
	End Catch
END
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Supplier_ShopAdmin_Select]    脚本日期: 04/09/2012 18:29:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<二个表Supplier ShopAdmin>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Supplier_ShopAdmin_Select](
	@SupplierID INT
)
AS
begin
	if exists(select Supplier.SupplierID,ShopAdmin.SupplierID from Supplier,ShopAdmin where Supplier.SupplierID=ShopAdmin.SupplierID and Supplier.SupplierID=@SupplierID)
	begin
	SELECT Supplier.SupplierID,Supplier.SupplierName,Supplier.Logo,Supplier.Description,Supplier.Address,Supplier.Phone,Supplier.Contacter,Supplier.Remark,
	Supplier.AddTime,Supplier.Banner,Supplier.ContactInfo,Supplier.Template,Supplier.PdtNum,Supplier.Status,Supplier.UpdateTime,
	Supplier.AuditTime,Supplier.Auditor,Supplier.AuditorName,Supplier.Shut,ShopAdmin.Password,Supplier.ExpireTime,Supplier.Reviews,
	Supplier.pj1,Supplier.pj2,Supplier.pj3,Supplier.pj4,Supplier.pj5,Supplier.Title,Supplier.Keyword,Supplier.Destn,Supplier.BankName,
	Supplier.BankAccount,Supplier.BankNo,Supplier.BankAddress,Supplier.CategoryNo,Supplier.BPRate,Supplier.PingFen,TopAD
	from Supplier,ShopAdmin where Supplier.SupplierID=ShopAdmin.SupplierID and Supplier.SupplierID=@SupplierID
	end
end








GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Supplier_ShopAdmin_Update]    脚本日期: 04/09/2012 18:29:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<根据SupplierID 更新二个表Supplier ShopAdmin>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Supplier_ShopAdmin_Update](
	@SupplierID INT,
	@SupplierName varchar(50),
	@Logo varchar(50),
	@Description nvarchar(1000),
	@Address varchar(200),
	@Phone varchar(50),
	@Contacter varchar(50),
	@Remark varchar(200),
	@Banner varchar(200),
	@ContactInfo varchar(500),
	@Auditor int,
	@AuditorName varchar(50),
	@ExpireTime	datetime,
	@Password varchar(20),
	@BankName varchar(50),
	@BankAccount varchar(10),
	@BankNo varchar(30),
	@BankAddress varchar(50),
	@CategoryNo varchar(20),
	@BPRate float,
	@TopAD ntext=NULL,
	@ErrorFlag int=1 out--返回0说明更新成功，-1则为更新失败
--	@ErrorMsg varchar(100) out --返回提示信息
)
AS
begin
set @ErrorFlag=1
Begin Try
begin Transaction
UPDATE	Supplier
SET	SupplierName = @SupplierName,
	logo = @logo,
	Description = @Description,
	Address = @Address,
	Phone = @Phone,
	Contacter = @Contacter,
	Remark = @Remark,
	Banner = @Banner,
	ContactInfo = @ContactInfo,
	Auditor = @Auditor,
	AuditorName = @AuditorName,
	ExpireTime = @ExpireTime,
	BankName=@BankName,
	BankAccount=@BankAccount,
	BankNo=@BankNo,
	BankAddress=@BankAddress,
	CategoryNo=@CategoryNo,
	BPRate=@BPRate,
	TopAD=@TopAD
WHERE SupplierID = @SupplierID

update ShopAdmin
set realname=@SupplierName 
WHERE SupplierID = @SupplierID

if(@password <>'')
begin
	UPDATE	ShopAdmin  SET	Password = @Password WHERE SupplierID = @SupplierID
end
set @ErrorFlag=0
commit transaction
End Try

Begin Catch
rollback tran
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
--select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
End Catch
END
















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SupplierInfo_Get]    脚本日期: 04/09/2012 18:29:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-11-15>
-- Description:	<获取商家前台显示用的商家基本信息和导航栏>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_SupplierInfo_Get]
@sid int--供应商ID
AS
BEGIN
	SET NOCOUNT ON;
	--商家基本信息
	select SupplierName,SupplierID,Logo,Description,Address, AddTime,Banner,ContactInfo,PdtNum,Reviews,pj1,pj2,pj3,pj4,pj5,PingFen,TopAD,Template from Supplier(nolock) where supplierid=@sid
	--商家导航栏
	select NavBarName,Link,Target,Inside from NavBar where supplierid=@sid order by Sort asc
END




















GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SupplierLogin_Select]    脚本日期: 04/09/2012 18:29:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_SupplierLogin_Select](
@username varchar(20),
@password varchar(20),
@result int=-1 output
)
AS
BEGIN
--	SET NOCOUNT ON;
	declare @id int ,@status int
--当找到有记录时，代表登录成功，但账号可能处于禁用状态。status=0代表禁用状态
	if exists(SELECT ID,Status FROM ShopAdmin(nolock) WHERE username=@username AND password = @password AND Status > 0)
	begin
		select id,username,password,flag,[power],supplierid,realname,phone,email,status,addtime from ShopAdmin (nolock) where username=@username AND password = @password AND Status > 0
	end
END





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SupplierPdt_Update]    脚本日期: 04/09/2012 18:29:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Hakkas>
-- Create date: <2011-04-12>
-- Description:	<创建商家商品>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_SupplierPdt_Update] 
@pid int,
@gid int,
@delpic varchar(200),
@addpic varchar(200)
AS
BEGIN
select * into #p1 from dbo.SplitToTable_Func(@addpic,'|')
select * into #p2 from dbo.SplitToTable_Func(@addpic,'|')
select pid=@pid,gid=@gid,p1.value as img1,p2.value as img2 into #p from #p1 p1,#p2 p2 where p1.id=p2.id
insert into pdtimg(pid,gid,img1,img2) select * from #p
END
/*
select * into #p1 from dbo.SplitToTable_Func('1.jpg|2.jpg|3.jpg|4.jpg','|')
select * into #p2 from dbo.SplitToTable_Func('1_s.jpg|2_s.jpg|3_s.jpg|4_s.jpg','|')
declare @pid int,@gid int
select  @pid=1,@gid=1
select pid=@pid,gid=@gid,p1.value as img1,p2.value as img2 into #p from #p1 p1,#p2 p2 where p1.id=p2.id
insert into pdtimg(pid,gid,img1,img2) select * from #p
drop table #p
drop table #p1
drop table #p2
*/

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Sys_CreateTableProc]    脚本日期: 04/09/2012 18:29:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Sys_Email_Send]    脚本日期: 04/09/2012 18:29:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



-- =============================================
-- Author:		<Hakkas@qq.com>
-- Create date: <2012-03-31>
-- Description:	<发送邮件>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_Sys_Email_Send] 
AS
BEGIN
declare @mailid int,
@email varchar(8000),
@subject varchar(8000),
@body varchar(8000),
@format varchar(20),
@itemid int,
@profilename varchar(50)

select @profilename='盈送数据库邮件配置'

declare email_cursor cursor for select mailid,ReceiverEmail,subject,body,format from emaillist where isnull(itemid,-1)=-1
open email_cursor
fetch next from email_cursor into @mailid,@email,@subject,@body,@format
while @@fetch_status = 0
begin
EXEC msdb.dbo.sp_send_dbmail 
     @profile_name=@profilename, 
     @recipients=@email,
	 @subject=@subject, 
     @body=@body, 
	 @body_format=@format,     
	 @mailitem_id=@itemid output
update emaillist set itemid=@itemid,issended=1,sendtime=getdate() where mailid=@mailid
fetch next from email_cursor into @mailid,@email,@subject,@body,@format
end
close email_cursor                                              
deallocate email_cursor
END




GO
/****** 对象:  StoredProcedure [dbo].[XpProc_SystemConfig_Select]    脚本日期: 04/09/2012 18:29:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2001-09-07>
-- Description:	<获取系统配置表>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_SystemConfig_Select] 
@configID int
AS
BEGIN
select  ConfigID,SiteName,SiteUrl,CompanyName,Linkman,Phone,Mobile,Email,Postalcode,Address,SiteLogo,
SiteTitle,MetaDescription,MetaKeywords,Copyright,SmtpServer,SmtpAccount,SmtpPassword,SmtpMailbox,
SmtpPort,SmtpValidate,SmtpCode,[DateFormat],MarkUnit,ShopStop,ShopStopWords,UseCache,CacheTime,
LinkAllowApply,LinkLogoWidth,LinkLogoHeight,UploadType,MaxFileSize,ProductPageSize,BulletinSizeInIndex,
NewProductSizeInIndex,HotProductSizeInIndex,CommendProductSizeInIndex,DiscountProductSizeInIndex,
[Language],TemplateFolder,StatsToolName,StatsCode,StatsLoginUrl,DefaultHeadAD,StorageAlert,
AliPaySettings,Settings,html,SCode,PhoneMessage,uKeyEnabled,UKeyCode,WatermarkText,MemberShowPrice,
ShowSort,XpShopADType,MemberMaxAddressCount,ProductReviewScore,TaxRate,RegScore,CardScore,ScoreRate,
CnzzStatus,CnzzAccount,PicWatermark,PicWatermarkPosition,PicWatermarkTransparent
from config
where configid=@configID
END


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Test_Add]    脚本日期: 04/09/2012 18:29:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[XpProc_Test_Add](
@errormsg varchar(1000) output
)
as
begin
select top 10  goodsid into #pdttemp3 from orderproduct 
	exec XpProc_Storage_Add 315 ,1,25,-1,2,'发货'
end

--declare @errormsg varchar(1000)
--exec XpProc_Test_Add @errormsg output




--20110717更新新了存储过程(百悦 爱悦已更新)
--1.XPProc_Storage_Add
--2.XpProc_OrderSendGoods_Add





GO
/****** 对象:  StoredProcedure [dbo].[XpProc_TGGoodsList_Select]    脚本日期: 04/09/2012 18:29:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[XpProc_TGGoodsList_Select](
@cid varchar(20)='0',--主分类
--@isnewest bit=null,--是否最新的一期团购
@pageSize int =16,--每页显示
@pageNo int=1,--页码
@number int=0,
@sort int,
@status int,
@totalpage int=null output,--总页数
@totalcount int=null output,--总记录数
@errorflag int=null output,
@errormsg varchar(200)=null output
)
as
begin
set nocount on
select @errorflag=0,@errormsg=''
if isnull(@pageno,0) > 0
select @pageno=@pageno-1
else
select @pageno=0

declare @sqlstr nvarchar(4000),@where nvarchar(4000)
select @where = ' p.productid=g.productid and g.ruleid=r.ruleid and g.basictype=''goods'' and g.subtype=''tuangou'' '

if isnull(@number,0)<>0
select @where=@where+' and r.ruleid='+convert(varchar(20),@number)

declare @temp varchar(30)
set @temp='order by g.id'
if isnull(@sort,0)<>0
begin
select @temp=case @sort when 1 then 'Order By pmtprice DESC'
			when 2 then 'Order By pmtprice ASC'
			when 3 then 'Order By balance asc'
			when 4 then 'Order By balance desc'
			when 5 then 'Order By endtime DESC'
			when 6 then 'Order By endtime ASC' end
end

if isnull(@status,0)<>0
begin
declare @temp1 varchar(100)
set @temp1=''
select @temp1=case @status when 1 then ' and r.begintime>getDate()'
			when 2 then ' and getdate() between r.begintime and r.endtime'
			when 3 then ' and r.endtime<getDate()' end
set @where=@where+@temp1
end

select @sqlstr='select * from (
select g.ID,pmtnumber-balance as AlreadyJoin,cast(minvalue as int)minvalue,
case when r.begintime<getDate() then ''0'' when r.endtime<getDate() then ''2''  when getdate() between r.begintime and r.endtime then ''1'' end as tgstatus
,p.productid,g.productname,g.pmtnumber,g.balance,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,r.ruleid,r.ruleno,goodsid,Row_number() over('

select @sqlstr=@sqlstr+@temp

select @sqlstr=@sqlstr+ ') as rowno 
from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) where ' + @where + ') as l where rowno>'+ convert(varchar(50),@pagesize*@pageno) + ' and rowno<=' + convert(varchar(50),@pagesize*(@pageno+1))
insert log(content)values(@sqlstr)

--获取分页商品datatable[1]
Execute(@sqlstr)

--获取总记录数和总页数
select @sqlstr = N'select @rows=(select max(rowno) from (select Row_number() over(order by g.pmtid desc) as rowno from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) where ' + @where + ') as temp)'
--print @sqlstr
--insert log(content)values(@sqlstr)
Execute sp_executesql @sqlstr, N'@rows int output', @totalcount output
select @totalcount=isnull(@totalcount,0)
select @totalpage=ceiling(@totalcount*1.0 / @pagesize)

--从product,Pmtrule,pmtgoods中取得类型为团购的商品
select g.ID,pmtnumber-balance as  AlreadyJoin, case  when r.begintime>getDate() then '0' when r.endtime<getDate() then '2'  when getdate() between r.begintime and r.endtime then '1' end as tgstatus,
p.productid,g.productname,g.pmtnumber,g.balance,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,r.ruleid,r.ruleno,goodsid
into #t from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) 
where g.ruleid=r.ruleid and r.subtype='tuangou' and p.productid=g.productid
--select *from #t
--drop table #t
select top 10 *from #t where tgstatus='0' order by id desc
select top 10 *from #t where tgstatus='1' order by id desc
select top 10 *from #t where tgstatus='2' order by id desc
end









GO
/****** 对象:  StoredProcedure [dbo].[XpProc_TGGoodsRelateInfo_Get]    脚本日期: 04/09/2012 18:29:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-08>
-- Description:	<获取团购商品详细页面的相关信息>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_TGGoodsRelateInfo_Get]
@id int,
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
--单个团购商品的信息
select top 1 g.ID,pmtnumber,cast(r.minvalue as int)minvalue,cast(r.maxvalue as int)maxvalue,pmtnumber-balance as AlreadyJoin,p.description,case when r.begintime>getDate() then '0' when r.endtime<getDate() then '2'  when getdate() between r.begintime and r.endtime then '1' end as TagStatus,
p.productid,g.productname,g.pmtnumber,g.balance,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,r.ruleid,r.ruleno,goodsid,GroupIDs,img2
from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock),pdtimg pg(nolock) where p.productid=g.productid and r.ruleid=g.ruleid and g.id=@id and p.productid=pg.pid

--从product,Pmtrule,pmtgoods中取得类型为团购的商品
select g.ID,pmtnumber-balance as  AlreadyJoin,case when r.begintime>getDate() then '0' when r.endtime<getDate() then '2'  when getdate() between r.begintime and r.endtime then '1' end as tgstatus,
p.productid,g.productname,g.pmtnumber,g.balance,p.shortdesc,p.marketprice,p.memberprice,p.imgfolder,p.ThumbnailImg,p.productimg,p.img5,g.pmtprice,r.begintime,r.endtime, datediff(d,getdate(),r.endtime) as leavingday,r.ruleid,r.ruleno,goodsid
into #t from product p(nolock),pmtgoods g(nolock),pmtrule r(nolock) 
where g.ruleid=r.ruleid and r.subtype='tuangou' and p.productid=g.productid

select top 10 *from #t where tgstatus='0' order by id desc
select top 10 *from #t where tgstatus='1' order by id desc
select top 10 *from #t where tgstatus='2' order by id desc


--一个团购商品的参于购买人
select m.name as membername,mb.addtime as times,mb.quantity as buysum from memberbooktg mb (nolock),member m(nolock),pmtgoods g(nolock) 
where g.id=@id and g.ruleid=mb.ruleid and g.goodsid=mb.goodsid and mb.memberid=m.memberid

end


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_TuanGou_Add]    脚本日期: 04/09/2012 18:29:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<hakkas@qq.com>
-- Create date: <2011-11-09>
-- Description:	<会员提交团购>
-- =============================================
CREATE PROCEDURE [dbo].[XpProc_TuanGou_Add]
@ruleid int,
@productid int,
@goodsid int=null,
@supplierid int=0,
@memberid int,
@addip varchar(50),
@receivername varchar(200),
@ReceiverAddress varchar(510),
@ReceiverPostalCode varchar(50),
@ReceiverPhone varchar(50),
@ReceiverMobile varchar(50),
@quantity int,--购买数量
@balance int output,
@errorflag int output,
@errormsg varchar(200) output
AS
BEGIN
select @balance=0,@errorflag=0,@errormsg=''
--insert log(content)values(@ruleid)
--insert log(content)values(@productid)
--insert log(content)values(@supplierid)
--insert log(content)values(@memberid)
--insert log(content)values(@addip)
--insert log(content)values(@receivername)
--insert log(content)values(@ReceiverAddress)
--insert log(content)values(@ReceiverPostalCode)
--insert log(content)values(@ReceiverPhone)
--insert log(content)values(@quantity)

Begin Try
declare @rulename varchar(100),@buyednum int,@limitednumber int,@islimited int,@ruleno varchar(20),@pmtprice decimal(18,2),@productname varchar(100),@begintime datetime,@endtime datetime
select @buyednum=0,@limitednumber=1
select @rulename=r.rulename,@balance=balance,@islimited=islimited,@limitednumber=limitednumber,@ruleno=r.ruleno,@pmtprice=g.pmtprice,@productname=g.productname,@begintime=r.begintime,@endtime=r.endtime
from pmtgoods g(nolock),pmtrule r(nolock) 
where g.ruleid=@ruleid and g.goodsid=@goodsid and g.ruleid=r.ruleid
--and getdate() between r.begintime and r.endtime
print('时间有效性判断开始')
if getdate()<@begintime
begin
select @errorflag=2,@errormsg='团购还未开始，请耐心等待'
return
end

if getdate()>@endtime
begin
select @errorflag=3,@errormsg='团购已结束'
return
end

print('数量有效性判断开始')
--团购数量，如果限制了团购的数量，这个balance就为商品的剩余数量，否为此为空代表团购数量不为
if (@balance>0 or @balance is null)
begin
--统计该会员已购买的团购商品
select @buyednum=isnull(sum(quantity),0) from memberbooktg where ruleid=@ruleid and goodsid=@goodsid and memberid=@memberid
if @islimited=1 and @quantity>@limitednumber-@buyednum
begin
select @errorflag=4,@errormsg='对不起，您已超出限制数量'
return
end
else
begin
--符合条件
--首先扣减该活动商品的剩余数量
	begin tran
	update pmtgoods set balance=balance-@quantity where ruleid=@ruleid and goodsid=@goodsid
	--记录该次团购记录
	INSERT memberbooktg
	(ruleid,rulename,ruleno, memberid, productid, goodsid,productname, quantity,pmtprice,addip,status,adduser,supplierid,receivername,ReceiverAddress,ReceiverPostalCode,ReceiverPhone,ReceiverMobile)
	VALUES 
	(@ruleid,@rulename, @ruleno, @memberid, @productid, @goodsid,@productname,@quantity,@pmtprice,@addip,0, @memberid,@supplierid,@receivername,@ReceiverAddress,@ReceiverPostalCode,@ReceiverPhone,@ReceiverMobile)
	commit
--返回剩余数量
select @balance=@balance-@quantity
end
end
else
begin
select @errorflag=5,@errormsg='对不起，商品已售完'
return
end
End Try

Begin Catch
-- 捕捉错误
rollback
select @errorflag=6
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
END







GO
/****** 对象:  StoredProcedure [dbo].[XpProc_UpdateFinanceStatus_Step1]    脚本日期: 04/09/2012 18:29:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<用于更新FinanceDetail,FinanceSummary的表,Status的六种状态为:-1无需结款，0不可结款，1未结款，2可结款 3结款中 4结款完成，这个存储过程在作业中调用，在每天的某个时刻运行>
-- =============================================

CREATE PROCEDURE  [dbo].[XpProc_UpdateFinanceStatus_Step1]
@ErrorFlag int output
AS
BEGIN
	begin transaction
	--Order.PayType <5说明的款到发货，=5是货到付款,这二种类型的订单从不可结款到未结款的状态的时间是不同的
	--款到发货：已经发货5天的订单可以进入结款期。
	--货到付款：已送达后7天的订单

	--通过联接Orders,FinanceDetail两个表，根据FinanceDetail的Status为0的纪录的OrderId，查找Orders表。 因此#temp存的是FinanceDetail中不可结款的记录。
	select a.orderid,a.SendTime,a.ReceiveTime,a.paytype,a.Status into #temp1 from orders(nolock) a join FinanceDetail(nolock) b on a.orderid=b.orderid and b.status=0
	--如果#temp的某个记录满足指定的条件则可以说明这个记录是可以从不可结款转变为未结款状态的，并通过OrderId 更新此记录在FinanceDetail中的Status=1
	update FinanceDetail set status=1 where orderid in(select orderid from #temp1 where 
	(isnull(SendTime,getDate())< dateadd(dd,-5, datediff(dd,0,getDate())) and paytype<5 ) or (isnull(ReceiveTime,getDate())< dateadd(dd,-7, datediff(dd,0,getDate())) and paytype>=5))
	
	--如果#temp的某个记录对应的orders  中的status=10,说明这个订单是还没有付款就取消了的
	--	update FinanceDetail set status=-1 where orderid in(select orderid from #temp1 where #temp1.status=10) 
	
	set @ErrorFlag=0
	Commit Transaction
END













GO
/****** 对象:  StoredProcedure [dbo].[XpProc_UpdateFinanceStatus_Step2]    脚本日期: 04/09/2012 18:29:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<用于更新FinanceIssue,FinanceDetail,FinanceSummary,FinanceSummaries的表，使财务状态从未结款转变为可结款状态
-- Status的六种状态为:-1无需结款，0不可结款，1未结款，2可结款 3结款中 4结款完成 ,
-- 这个存储过程程只在作业中调用，在一个月的几个时间段运行>
-- =============================================

CREATE PROCEDURE  [dbo].[XpProc_UpdateFinanceStatus_Step2]
@errorFlag int =0 output,
@errorMessage varchar(20) output
AS
BEGIN

--设置每月定时运行的时间
declare @time1 int,@time2 int,@time3 int ,@time4 int
set @time1=5
set @time2=10
set @time3=20 
set @time4=25
declare @curday smalldatetime 
set @curday=day(getDate())
if not(@curday=@time1 or @curday=@time2 or @curday=@time3 or @curday=@time4 )
begin
	select @errorFlag=0
	select @errorMessage='不是结算日期'
	return
end
    
--生成期数,插入到FinanceIssue表中去
declare @issue varchar(50)		
if not exists(select top 1 Issue from FinanceIssue(nolock) ) --没有期数时，要生成它
begin
	select @issue=convert(varchar(10),dateadd(dd,0,getDate()),112)
	insert FinanceIssue values(@issue,getDate(),getDate());
end
else
begin
	declare @NewStartTime smalldatetime 
	select @NewStartTime=dateadd(dd,1,EndTime) from FinanceIssue --设置本期的开始时间，值为上期的结束时间+1天
	select @issue=convert(varchar(10),dateadd(dd,0,getDate()),112) --设置本期的期数，值为表示当前时间的年月日的字符串
	if not exists(select top 1 * from FinanceIssue where Issue=@issue)
	insert FinanceIssue values(@issue,@NewStartTime,getDate());
end

declare @status int 
set @status=2

begin try
select sum(amount)as amount,sum(tuikuan)as tuikuan,sum(yongjin)as yongjin,supplierid into #temp2 from FinanceDetail(nolock) where status=1 group by supplierid
--判断是否有要更新的财务记录
if exists(select top 1 * from #temp2)
begin
	BEGIN TRANSACTION
	--更新FinanceDetail明细表中的期数跟Status
	update FinanceDetail set Status=2, issue=@issue where status=1
	--每个供应商在特定的期数内只有一条记录，如果期数已存在则更新，没有的话就要插入新的纪录
	if exists(select top 1 * from FinanceSummary where issue=@issue)
	delete from FinanceSummary where issue=@issue
	select sum(amount)as amount,sum(tuikuan)as tuikuan,sum(yongjin)as yongjin,supplierid into #temp3 from FinanceDetail(nolock) where status=2 and issue=@issue group by supplierid
	insert FinanceSummary(issue,amount,tuikuan,yongjin,supplierid,status) select @issue,*,@status from #temp3

	--更新完成后，向FinanceSummaries表中插入按Issue分组的记录
	--在FinanceSumaries中特定的期数只有一条记录，如果期数已存在则更新
	select sum(amount)as amount,sum(tuikuan)as tuikuan,sum(yongjin)as yongjin into #temp 
	from FinanceSummary(nolock) where Issue=@Issue and status=@status group by Issue
	if exists(select top 1 * from FinanceSummaries where Issue=@Issue and status=@status)
	begin
	update FinanceSummaries set amount=#temp.amount,tuikuan=#temp.tuikuan,yongjin=#temp.yongjin 
	from #temp where issue=@issue
	end
	else
	begin
	insert FinanceSummaries(issue,amount,tuikuan,yongjin,status) select @issue,*,@status from #temp
	end

	set @errorFlag=0
    set @errorMessage='操作已完成'
	Commit Transaction
END
else
begin
	set @errorFlag=0
    set @errorMessage='没有可操作的记录，操作已完成'
end
end try
Begin Catch
-- 捕捉错误
rollback tran
select @errorflag=1
select @errorMessage = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
end

--declare @error int 
--declare @message varchar(2000)
--exec XpProc_UpdateFinanceStatus_Step2 @error output,@message output
--select @error,@message



GO
/****** 对象:  StoredProcedure [dbo].[XpProc_UpdateFinanceStatus_Step3]    脚本日期: 04/09/2012 18:29:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<用于更新FinanceDetail,FinanceSummary，FinanceSummaries的表的Status为3，3表示结款中 >
-- =============================================

CREATE PROCEDURE  [dbo].[XpProc_UpdateFinanceStatus_Step3](
@Issue varchar(50),
@SupplierID int=null,
@Error int =-1 output
)
AS
BEGIN
	Begin Transaction
	--通过更新FinanceSummaries中的Status为3，同时通过ISSUE更新相关的FinanceDetail,FinanceSummary表
	--一次性全部更新所有商家某一个期号为结款中，直接把FinanceSummaries，FinanceDetail，FinanceSummary表中符合条件的 status置为3
	if(@supplierid is null)
	begin
		--当FinanceSummaries表的某个期号是满足条件的记录Status=3时，直接返回，不用更改它表的状态了		
		if exists(select top 1 * from FinanceSummaries(nolock) where status=3 and issue=@issue)
		begin
		set @Error=0
		commit transaction
		return
		end
		else --直接更新FinanceSummaries，FinanceDetail，FinanceSummary三个表中符合条件的 status置为3
		begin
		update FinanceSummaries set status=3 where issue=@issue and status=2
		update FinanceDetail set status=3 where issue=@issue and status=2
		update FinanceSummary set status=3 where Issue=@Issue and status=2
		end
	end
	--通过更新FinanceSummary表中满足条件的Status=3,同时通过ISSUE更新相关的FinanceDetail,FinanceSummaries表
	else
	begin
		--当FinanceSummary表的某个期号是满足条件的记录已经是Status=3时，直接返回，不用更改其表的状态了	
		if exists(select top 1 * from FinanceSummary(nolock) where status=3 and supplierid=@supplierid  and issue=@issue)
		begin
		set @Error=0
		commit transaction
		return
		end
		else --更新FinanceSummaries，FinanceDetail，FinanceSummary三个表中符合条件的 status置为3
		begin
		update FinanceSummary set status=3 where Issue=@Issue and status=2 and supplierid=@supplierid
		update FinanceDetail set status=3 where issue=@issue and status=2 and supplierid=@supplierid
		--判断Financesummaries表的期数为@issue的记录，Status是否满足变为3的条件，只有Financesummary表的期数为@issue的所有记录status=3,才能把FinanceSummaries中的Status置为4
		declare @totalIssue int --@issue期数的总数
		declare @state3Issue int --@issue中Status为3的个数
		select @totalIssue=count(issue) from FinanceSummary(nolock) where issue=@issue
		select @state3Issue=count(issue) from FinanceSummary(nolock) where issue=@issue and status=3
		if(@totalIssue=@state3Issue)
		update FinanceSummaries set status=3 where Issue=@Issue and status=2
		end
	end
	set @Error=0
	commit transaction
end 

--测试用
--declare @error int 
--exec XpProc_UpdateFinanceStatus_Step3 '20110315',10001,@error output
--select @error
GO
/****** 对象:  StoredProcedure [dbo].[XpProc_UpdateFinanceStatus_Step4]    脚本日期: 04/09/2012 18:29:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<用于更新FinanceDetail,FinanceSummary，FinanceSummaries的表的Status为4，4结款完成>
-- =============================================

CREATE PROCEDURE  [dbo].[XpProc_UpdateFinanceStatus_Step4](
@financeissueid int=null,
@Issue varchar(50)=null,
@SupplierID int=null,
@serialnumber varchar(200)=null,
@remark varchar(1000)=null,
@adminid int =null,
@realname varchar(20)=null,
@errorflag int output,
@errormsg varchar(200) output
)
AS
BEGIN
begin try
Begin Transaction
	select @errorflag=1;
	select @errormsg='';
	--一次性全部更新所有商家某一个期号为结款完成，直接把FinanceSummaries，FinanceDetail，FinanceSummary表中符合条件的 status置为4
	if(@supplierid is null)
	begin
		--当FinanceSummaries表的某个期号是满足条件的记录Status=4时，直接返回，不用更改其它的状态了		
		if exists(select top 1 * from FinanceSummaries(nolock) where status=4 and issue=@issue)
		begin
		set @errorflag=0
		set @errormsg='不需要更新'
		commit transaction
		return
		end
		else --直接更新FinanceSummaries，FinanceDetail，FinanceSummary三个表中符合条件的 status置为3
		begin
		update FinanceSummaries set status=4 where issue=@issue and status=3
		update FinanceDetail set status=4 where issue=@issue and status=3
		update FinanceSummary set status=4 where Issue=@Issue and status=3
		end
	end
	else --只是更新某个商家的某期号为结款完成，
	begin
		--当FinanceSummaries表的某个期号是满足条件的记录Status=4时，直接返回，不用更改其它的状态了		
		if exists(select top 1 * from FinanceSummary(nolock) where status=4 and issue=@issue and supplierid=@supplierid)
		begin
		set @errorflag=0
		set @errormsg='不需要更新'
		commit transaction
		return
		end
		else --直接更新FinanceSummaries，FinanceDetail，FinanceSummary三个表中符合条件的 status置为4
		begin
        declare @temp varchar(8000)--日志写到financesummary表中去
		declare @datetime nvarchar(20)
		select @datetime=convert(char(4),getdate(),120)+N'年'+right(convert(char(7),getdate(),120),2)+N'月'+
		right(convert(char(10),getdate(),120),2)+N'日'
		select @temp='ID为'+cast(@adminid as varchar(10))+'的操作员 '+@realname+'在'+@datetime+' 跟商家结款完成'+ ' 交易流水号为: '+@serialnumber+' 备注: '+@remark
		update FinanceSummary set status=4 ,remark=isnull(remark,'')+@temp where Issue=@Issue and status=3 and supplierid=@supplierid
		update FinanceDetail set status=4 where issue=@issue and status=3 and supplierid=@supplierid
		--判断Financesummaries表的期数为@issue的记录，Status是否满足变为4的条件，只有Financesummary表的期数为@issue的所有记录status=4时，才可把FinanceSummaries表的期数为@issue的记录，Status置为4
		declare @totalIssue int --@issue期数的总数
		declare @state4Issue int --@issue中Status为4的个数
		select @totalIssue=count(issue) from FinanceSummary(nolock) where issue=@issue
		select @state4Issue=count(issue) from FinanceSummary(nolock) where issue=@issue and status=4
		if(@totalIssue=@state4Issue)
		update FinanceSummaries set status=4 where Issue=@Issue and status=3
		end
	end
    set @errorflag=0
	set @errormsg='状态更新成功'
 	Commit Transaction
End Try
Begin Catch
-- 捕捉错误
print ERROR_MESSAGE()
select @errorflag=1
select @errormsg = 'error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE();
Return
End Catch
end

--20111214
--set ANSI_NULLS ON
--set QUOTED_IDENTIFIER ON
--GO
----GO
---- =============================================
---- Author:		<Author,,Name>
---- Create date: <Create Date,,>
---- Description:	<用于更新FinanceDetail,FinanceSummary，FinanceSummaries的表的Status为4，4结款完成>
---- =============================================
--
--ALTER PROCEDURE  [dbo].[XpProc_UpdateFinanceStatus_Step4](
--@Issue varchar(50),
--@SupplierID int=null,
--@Error int =-1 output
--)
--AS
--BEGIN
--Begin Transaction
--	--一次性全部更新所有商家某一个期号为结款完成，直接把FinanceSummaries，FinanceDetail，FinanceSummary表中符合条件的 status置为4
--	if(@supplierid is null)
--	begin
--		--当FinanceSummaries表的某个期号是满足条件的记录Status=4时，直接返回，不用更改其它的状态了		
--		if exists(select top 1 * from FinanceSummaries(nolock) where status=4 and issue=@issue)
--		begin
--		set @Error=0
--		commit transaction
--		return
--		end
--		else --直接更新FinanceSummaries，FinanceDetail，FinanceSummary三个表中符合条件的 status置为3
--		begin
--		update FinanceSummaries set status=4 where issue=@issue and status=3
--		update FinanceDetail set status=4 where issue=@issue and status=3
--		update FinanceSummary set status=4 where Issue=@Issue and status=3
--		end
--	end
--	else --只是更新某个商家的某期号为结款完成，
--	begin
--		--当FinanceSummaries表的某个期号是满足条件的记录Status=4时，直接返回，不用更改其它的状态了		
--		if exists(select top 1 * from FinanceSummary(nolock) where status=4 and issue=@issue and supplierid=@supplierid)
--		begin
--		set @Error=0
--		commit transaction
--		return
--		end
--		else --直接更新FinanceSummaries，FinanceDetail，FinanceSummary三个表中符合条件的 status置为4
--		begin
--		update FinanceSummary set status=4 where Issue=@Issue and status=3 and supplierid=@supplierid
--		update FinanceDetail set status=4 where issue=@issue and status=3 and supplierid=@supplierid
--		--判断Financesummaries表的期数为@issue的记录，Status是否满足变为4的条件，只有Financesummary表的期数为@issue的所有记录status=4时，才可把FinanceSummaries表的期数为@issue的记录，Status置为4
--		declare @totalIssue int --@issue期数的总数
--		declare @state4Issue int --@issue中Status为4的个数
--		select @totalIssue=count(issue) from FinanceSummary(nolock) where issue=@issue
--		select @state4Issue=count(issue) from FinanceSummary(nolock) where issue=@issue and status=4
--		if(@totalIssue=@state4Issue)
--		update FinanceSummaries set status=4 where Issue=@Issue and status=3
--		end
--	end
--    set @Error=0
-- 	Commit Transaction
--end 
----declare @error int 
----exec XpProc_UpdateFinanceStatus_Step4 '20110325',10002,@error output
----select @error
--

GO
/****** 对象:  StoredProcedure [dbo].[XpProc_Vote_Add]    脚本日期: 04/09/2012 18:29:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[XpProc_Vote_Add](
@mid int,--会员ID
@id int,--评价ID
@type int, --投票类型 3商家评价
@flag int,--标识位,标识是投有用还是无用的 ,1有用 0无用
@errorFlag int output,
@errormsg varchar(100) output
)
as
begin
if exists (select VoteRecordID from VoteRecord where MemberID = @mid  and ObjID = @id and VoteType =@type)
begin
set @errorFlag=1
set @errorMsg='你已经投过票了，不能重复投票'
return 
end
--评论ID是否存在
if(@type=3)
begin
	if not exists(select shopevalid from shopeval where shopevalid=@id)
	begin
	set @errorFlag=1
	set @errorMsg='商家评论不存在'
	return
	end
end

--更新评价表里的有用跟无用的投票数
begin try
begin tran
if(@flag=1)
begin
if(@type=3)
UPDATE ShopEval Set YesNum=YesNum+1 Where ShopEvalid =@id
end
else
begin
if(@type=3)
UPDATE ShopEval Set NotNum=NotNum+1 Where ShopEvalid =@id
end

--插入会员的投票记录
declare @VoteRecordID int 
select @VoteRecordID=max(VoteRecordID)+1 from VoteRecord
INSERT INTO VoteRecord (VoteRecordID,MemberID,ObjID,VoteType) VALUES ( @VoteRecordID,@mid,@id,@type)
set @errorFlag=0
set @errorMsg='投票成功'
commit tran
end try

begin catch
rollback
set @errorflag=1
set @errorMsg='投票失败'
--insert log(content) values('error line: ' + CAST(ERROR_LINE() AS varchar(8)) + ', error number: ' + CAST(ERROR_NUMBER() AS varchar(8)) + ', error message: ' + ERROR_MESSAGE())
end catch
end


GO
/****** 对象:  StoredProcedure [dbo].[XpProc_XpFinanceLog_Insert]    脚本日期: 04/09/2012 18:29:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<liwenhai>
-- Create date: <2011-11-26>
-- Description:	<添加推广提成金额日志>


-- =============================================
Create PROC [dbo].[XpProc_XpFinanceLog_Insert]
	@MemberID int,
	@Mobile varchar(20) = NULL,
	@Finance decimal(18, 2),
	@Flag int,
	@NeedSend bit = NULL,
	@IsSended bit = NULL,
	@SendTime datetime = NULL,
	@FinanceType varchar(50) = NULL,
	@FromID varchar(100) = NULL,
	@FromRemark varchar(100) = NULL,
	@Remark varchar(200) = NULL,
	@AddIP varchar(50) = NULL,
	@GenerateTime datetime = NULL,
	@AddTime datetime = NULL,
	@AddUser int = NULL,
	@AddUserName varchar(50) = NULL	
AS
--如果是扣减积分，传过来的积分数又是正数的，要变成负数
if @Flag=-1 and @Finance>0
select @Finance=-@Finance
--计算增加后的积分
declare @prefinance decimal(18,2),@newfinance  decimal(18,2)
select @prefinance=isnull(finance,0) from member(nolock) where memberid=@memberid
select @newfinance=@prefinance+@Finance
--更改会员积分
update member set finance=@newfinance where memberid=@memberid
--写入积分日志
INSERT xpfinancelog(
MemberID, Mobile,Prefinance,finance,Totalfinance, Flag, NeedSend, IsSended, SendTime,financeType, FromID, 
FromRemark, Remark, AddIP, GenerateTime, AddTime, AddUser, AddUserName
)
VALUES (
@MemberID, @Mobile,@prefinance,@finance,@newfinance,@Flag, COALESCE(@NeedSend, (1)), COALESCE(@IsSended, (0)), @SendTime, @financeType, @FromID, 
@FromRemark, @Remark, @AddIP, COALESCE(@GenerateTime, getdate()), COALESCE(@AddTime, getdate()), COALESCE(@AddUser, -1), COALESCE(@AddUserName,'system')
)

GO
/****** 对象:  StoredProcedure [dbo].[XpShop_SheQu_Update]    脚本日期: 04/09/2012 18:29:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[XpShop_SheQu_Update]
(
	@sqid int,
	@sqno nvarchar(20),
	@sqname varchar(20),
	@province int,
	@city int,
	@county int,
	@address varchar(50),
	@haveService bit,
	@linkPeople varchar(10),
	@faxNumber varchar(20),
	@linkPhone varchar(20),
	@linkMobile varchar(20),
	@status int,
	@addUser varchar(10),
	@addTime datetime,
	@updateUser varchar(10),
	@updateTime datetime,
	@auditUser varchar(10),
	@auditTime datetime,
	@remark varchar(100)

)
AS
BEGIN
	insert into log(content) values(convert(varchar(20),@sqid)+@sqname)
	IF EXISTS (SELECT * FROM SheQu WHERE sqid = @sqid)
	BEGIN
		UPDATE	SheQu
		SET		sqno=@sqno,
				sqname=@sqname,
				Province=@province,
				City=@city,
				County=@county,
				Address=@address,
				HaveService=@haveService,
				LinkPeople=@linkPeople,
				FaxNumber=@faxNumber,
				LinkPhone=@linkPhone,
				LinkMobile=@linkMobile,
				Status=@status,
				UpdateUser=@updateUser,
				UpdateTime=@updateTime,
				Remark=@remark
		WHERE	sqid = @sqid
	END
	ELSE
	BEGIN
		INSERT	SheQu( sqno, sqname, Province, City, County, Address, HaveService, LinkPeople, FaxNumber, LinkPhone, LinkMobile, Status, AddUser, AddTime, Remark)
		VALUES	(@sqno,
				 @sqname,
				 @province,
				 @city,
				 @county,
				 @address,
				 @haveService,
				 @linkPeople,
				 @faxNumber,
				 @linkPhone,
				 @linkMobile,
				 @status,
				 @addUser,
				 @addTime,
				 @remark)
	END
END