/****** Object:  Database [Hishop]    Script Date: 04/20/2009 16:21:45 ******/
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'microsoft_database_tools_deploystamp' , NULL,NULL, NULL,NULL, NULL,NULL))
EXEC dbo.sp_addextendedproperty @name=N'microsoft_database_tools_deploystamp', @value=N'0ec44c5b-eecb-4d6c-b883-7b9be8833fb9'
GO
/****** Object:  Role [hishopdev_user]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'hishopdev_user')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'hishopdev_user' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'hishopdev_user'

END
GO
/****** Object:  Role [aspnet_Membership_BasicAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Membership_BasicAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Membership_BasicAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Membership_BasicAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_Membership_FullAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Membership_FullAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Membership_FullAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Membership_FullAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_Membership_ReportingAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Membership_ReportingAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Membership_ReportingAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Membership_ReportingAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_Personalization_BasicAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Personalization_BasicAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Personalization_BasicAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Personalization_BasicAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_Personalization_FullAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Personalization_FullAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Personalization_FullAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Personalization_FullAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_Personalization_ReportingAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Personalization_ReportingAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Personalization_ReportingAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Personalization_ReportingAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_Profile_BasicAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Profile_BasicAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Profile_BasicAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Profile_BasicAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_Profile_FullAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Profile_FullAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Profile_FullAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Profile_FullAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_Profile_ReportingAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Profile_ReportingAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Profile_ReportingAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Profile_ReportingAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_Roles_BasicAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Roles_BasicAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Roles_BasicAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Roles_BasicAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_Roles_FullAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Roles_FullAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Roles_FullAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Roles_FullAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_Roles_ReportingAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Roles_ReportingAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Roles_ReportingAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_Roles_ReportingAccess', @ownername = N'dbo'

END
GO
/****** Object:  Role [aspnet_WebEvent_FullAccess]    Script Date: 04/20/2009 16:21:46 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_WebEvent_FullAccess')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_WebEvent_FullAccess' AND issqlrole = 1)
EXEC dbo.sp_addrole @rolename = N'aspnet_WebEvent_FullAccess', @ownername = N'dbo'

END
GO
/****** Object:  Table [dbo].[Hishop_ProductConsultations]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ProductConsultations]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ProductConsultations](
	[ConsultationId] [int] IDENTITY(1,1) NOT NULL,
	[ProductId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[UserName] [nvarchar](100) NOT NULL,
	[UserEmail] [nvarchar](100) NOT NULL,
	[ConsultationText] [nvarchar](1000) NOT NULL,
	[ConsultationDate] [datetime] NOT NULL,
	[ReplyText] [nvarchar](1000) NULL,
	[ReplyDate] [datetime] NULL,
	[ReplyUserId] [int] NULL,
 CONSTRAINT [PK_Hishop_ProductConsultations] PRIMARY KEY CLUSTERED 
(
	[ConsultationId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_AttributeValues]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_AttributeValues]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_AttributeValues](
	[AttributeId] [int] NOT NULL,
	[ValueStr] [nvarchar](200) NOT NULL
)
END
GO
/****** Object:  Table [dbo].[aspnet_SchemaVersions]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_SchemaVersions]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[aspnet_SchemaVersions](
	[Feature] [nvarchar](128) NOT NULL,
	[CompatibleSchemaVersion] [nvarchar](128) NOT NULL,
	[IsCurrentVersion] [bit] NOT NULL,
 CONSTRAINT [PK__aspnet_SchemaVer__03317E3D] PRIMARY KEY CLUSTERED 
(
	[Feature] ASC,
	[CompatibleSchemaVersion] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_EmailTemplet]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_EmailTemplet]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_EmailTemplet](
	[EmailType] [nvarchar](100) NOT NULL,
	[EmailPriority] [int] NOT NULL,
	[TagDescription] [nvarchar](500) NULL,
	[EmailDescription] [nvarchar](500) NULL,
	[EmailSubject] [nvarchar](1024) NULL,
	[EmailBody] [ntext] NULL,
 CONSTRAINT [PK_Hishop_EmailTemplet] PRIMARY KEY CLUSTERED 
(
	[EmailType] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_BannedNetworks]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_BannedNetworks]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_BannedNetworks](
	[BannedNetworkID] [int] IDENTITY(1,1) NOT NULL,
	[StartingAddress] [nvarchar](50) NOT NULL,
	[EndingAddress] [nvarchar](50) NOT NULL,
	[BannedDate] [datetime] NULL,
 CONSTRAINT [PK_Hishop_BannedNetworks] PRIMARY KEY CLUSTERED 
(
	[BannedNetworkID] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_ProductImages]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ProductImages]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ProductImages](
	[ProductImageId] [int] IDENTITY(1,1) NOT NULL,
	[ProductId] [int] NOT NULL,
	[ImageUrl] [nvarchar](255) NOT NULL,
 CONSTRAINT [PK_Hishop_ProductImages_1] PRIMARY KEY CLUSTERED 
(
	[ProductImageId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_PromoteSales_Fee]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PromoteSales_Fee]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PromoteSales_Fee](
	[ActivityId] [int] NOT NULL,
	[Amount] [money] NOT NULL,
	[ShipChargeFree] [bit] NOT NULL,
	[ServiceChargeFree] [bit] NOT NULL,
	[PackingChargeFree] [bit] NOT NULL,
 CONSTRAINT [PK_Hishop_PromoteSales_Fee] PRIMARY KEY CLUSTERED 
(
	[ActivityId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_ProductPrices]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ProductPrices]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ProductPrices](
	[RankId] [int] NOT NULL,
	[ProductId] [int] NOT NULL,
	[SalePrice] [money] NULL,
 CONSTRAINT [PK_Hishop_ProductPrices] PRIMARY KEY CLUSTERED 
(
	[RankId] ASC,
	[ProductId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_ProductNotify]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ProductNotify]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ProductNotify](
	[Email] [nvarchar](100) NOT NULL,
	[ProductId] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_ProductNotify] PRIMARY KEY CLUSTERED 
(
	[ProductId] ASC,
	[Email] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_MemberOrders_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_MemberOrders_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_MemberOrders_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@TotalUserOrders int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForUserOrders
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		OrderId nvarchar(50),
		PublishDate datetime
	)	

	INSERT INTO #PageIndexForUserOrders(OrderId,PublishDate)
	Exec sp_executesql @sqlPopulate

	SET @TotalUserOrders = @@rowcount
	
	SELECT O.*,o.OrderTotal AS OrderPrice,
        (select count(LeaveId) from Hishop_OrderLeaveWords where OrderId = O.OrderId and IsMemberVisited=0 ) as NoVisitNum,
        (select count(LeaveId) from Hishop_OrderLeaveWords where OrderId = O.OrderId ) as VisitNum
	FROM Hishop_Orders O, #PageIndexForUserOrders
	WHERE 
		O.OrderId = #PageIndexForUserOrders.OrderId AND
		#PageIndexForUserOrders.IndexId > @PageLowerBound AND
		#PageIndexForUserOrders.IndexId < @PageUpperBound 
	ORDER BY #PageIndexForUserOrders.IndexId
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_OrderActionHistorys]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_OrderActionHistorys]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_OrderActionHistorys](
	[OrderId] [nvarchar](50) NOT NULL,
	[UserId] [int] NOT NULL,
	[Username] [nvarchar](64) NOT NULL,
	[ActionCode] [nvarchar](100) NOT NULL,
	[ActionDate] [datetime] NOT NULL
)
END
GO
/****** Object:  Table [dbo].[Hishop_InpourRequest]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_InpourRequest]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_InpourRequest](
	[InpourId] [bigint] IDENTITY(10000,1) NOT NULL,
	[TradeDate] [datetime] NOT NULL,
	[InpourBlance] [money] NOT NULL,
	[UserId] [int] NOT NULL,
	[PaymentGateway] [nvarchar](50) NULL
)
END
GO
/****** Object:  Table [dbo].[Hishop_ShippingAreas]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ShippingAreas]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ShippingAreas](
	[AreaId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Hishop_ShippingAreas] PRIMARY KEY CLUSTERED 
(
	[AreaId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_BalanceDetails]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_BalanceDetails]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_BalanceDetails](
	[JournalNumber] [bigint] IDENTITY(1,1) NOT NULL,
	[UserId] [int] NOT NULL,
	[TradeDate] [datetime] NOT NULL,
	[TradeType] [int] NOT NULL,
	[Income] [money] NULL,
	[Expenses] [money] NULL,
	[Balance] [money] NOT NULL,
	[Payer] [int] NULL,
	[Payee] [int] NULL,
	[Remark] [nvarchar](2000) NULL,
 CONSTRAINT [PK_Hishop_BalanceDetails] PRIMARY KEY CLUSTERED 
(
	[JournalNumber] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_SKUs]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_SKUs]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_SKUs](
	[SKU] [nvarchar](50) NOT NULL,
	[ProductId] [int] NOT NULL,
	[Stock] [int] NULL,
	[Price] [money] NULL,
	[AttributeNames] [nvarchar](500) NULL,
	[AttributeValues] [nvarchar](500) NULL,
 CONSTRAINT [PK_Hishop_SKUs] PRIMARY KEY CLUSTERED 
(
	[SKU] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_ProductExtendCategories]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ProductExtendCategories]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ProductExtendCategories](
	[CategoryId] [int] NOT NULL,
	[ProductId] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_ProductExtendCategories] PRIMARY KEY CLUSTERED 
(
	[CategoryId] ASC,
	[ProductId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_PromoteSales_Give]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PromoteSales_Give]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PromoteSales_Give](
	[ActivityId] [int] NOT NULL,
	[BuyQuantity] [int] NOT NULL,
	[GiveQuantity] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_PromoteSales_Give] PRIMARY KEY CLUSTERED 
(
	[ActivityId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Setup_RemoveAllRoleMembers]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Setup_RemoveAllRoleMembers]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Setup_RemoveAllRoleMembers]
    @name   sysname
AS
BEGIN
    CREATE TABLE #aspnet_RoleMembers
    (
        Group_name      sysname,
        Group_id        smallint,
        Users_in_group  sysname,
        User_id         smallint
    )

    INSERT INTO #aspnet_RoleMembers
    EXEC sp_helpuser @name

    DECLARE @user_id smallint
    DECLARE @cmd nvarchar(500)
    DECLARE c1 cursor FORWARD_ONLY FOR
        SELECT User_id FROM #aspnet_RoleMembers

    OPEN c1

    FETCH c1 INTO @user_id
    WHILE (@@fetch_status = 0)
    BEGIN
        SET @cmd = ''EXEC sp_droprolemember '' + '''''''' + @name + '''''', '''''' + USER_NAME(@user_id) + ''''''''
        EXEC (@cmd)
        FETCH c1 INTO @user_id
    END

    CLOSE c1
    DEALLOCATE c1
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_PromoteSales_QuantityDiscount]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PromoteSales_QuantityDiscount]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PromoteSales_QuantityDiscount](
	[ActivityId] [int] NOT NULL,
	[Quantity] [int] NOT NULL,
	[DiscountValue] [money] NOT NULL,
 CONSTRAINT [PK_Hishop_PromoteSales_QuantityDiscount] PRIMARY KEY CLUSTERED 
(
	[ActivityId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_CategoryProductPriceGlobalSetLog]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_CategoryProductPriceGlobalSetLog]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_CategoryProductPriceGlobalSetLog](
	[RecordId] [int] IDENTITY(1,1) NOT NULL,
	[OperateDate] [datetime] NOT NULL,
	[CategoryId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[Remark] [nvarchar](4000) NULL,
	[MarketPriceOperate] [nchar](1) NULL,
	[SalePriceOperate] [nchar](1) NULL,
	[CostPriceOperate] [nchar](1) NULL,
	[MarketPrice] [money] NULL,
	[SalePrice] [money] NULL,
	[CostPrice] [money] NULL,
 CONSTRAINT [PK_Hishop_CategoryProductPriceGlobalSetLog] PRIMARY KEY CLUSTERED 
(
	[RecordId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_Suppliers]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Suppliers]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Suppliers](
	[SupplierId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[TelPhone] [nvarchar](50) NULL,
	[CellPhone] [nvarchar](50) NULL,
	[Address] [nvarchar](500) NULL,
	[Remark] [nvarchar](1000) NULL,
	[Contact] [nvarchar](50) NULL,
 CONSTRAINT [PK_Hishop_Suppliers] PRIMARY KEY CLUSTERED 
(
	[SupplierId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_BannedAddresses]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_BannedAddresses]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_BannedAddresses](
	[NetworkAddress] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
	[BannedDate] [datetime] NOT NULL,
 CONSTRAINT [PK_Hishop_BannedAddresses] PRIMARY KEY CLUSTERED 
(
	[NetworkAddress] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_PromoteSales_Gifts]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PromoteSales_Gifts]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PromoteSales_Gifts](
	[ActivityId] [int] NOT NULL,
	[GiftId] [int] NOT NULL,
	[GiftPrice] [money] NULL,
 CONSTRAINT [PK_Hishop_PromoteSales_Gifts_1] PRIMARY KEY CLUSTERED 
(
	[ActivityId] ASC,
	[GiftId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_CategoryProductPriceGlobalSet_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_CategoryProductPriceGlobalSet_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_CategoryProductPriceGlobalSet_Get]
(
 	@PageIndex		 INT,
	@PageSize		 INT,
	@IsCount	     BIT,
    @SqlPopulate     NTEXT  
)
as
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @TotalRecords	INT
   
	SET @TotalRecords = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		RecordId BIGINT,
	)
	
	INSERT INTO #PageIndexForSearch (RecordId)
	Exec sp_executesql @SqlPopulate
	
    SET @TotalRecords = @@rowcount
	
	 SELECT
		c.*,
		(select UserName from vw_Users_FullUser where Hi_UserId=c.UserId) as UserName,
        (select Name from Hishop_Categories where CategoryId=c.CategoryId) as CategoryName
	FROM 
		Hishop_CategoryProductPriceGlobalSetLog c (nolock),
		#PageIndexForSearch
	WHERE 
		c.RecordId = #PageIndexForSearch.RecordId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
        
	ORDER BY
		#PageIndexForSearch.IndexId
END

   SELECT @TotalRecords' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_DefaultMemberRank_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_DefaultMemberRank_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_DefaultMemberRank_Get]
	(
	@IsMemberCreated bit,
	@CreatorUserId int 
	)
AS
	if @IsMemberCreated = 1
		SELECT RankId FROM Hishop_UserRanks WHERE IsDefault= 1 AND IsMemberCreated = 1 AND CreatorUserId = @CreatorUserId
	else
		SELECT RankId FROM Hishop_UserRanks WHERE IsDefault= 1 AND IsMemberCreated = 0' 
END
GO
/****** Object:  Table [dbo].[Hishop_Coupons]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Coupons]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Coupons](
	[CouponId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[EnabledTimes] [int] NOT NULL,
	[ClosingTime] [datetime] NOT NULL,
	[Description] [ntext] NULL,
	[Amount] [money] NULL,
	[DiscountValue] [money] NOT NULL,
 CONSTRAINT [PK_Hishop_Coupons] PRIMARY KEY CLUSTERED 
(
	[CouponId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_ProductAttributes]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ProductAttributes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ProductAttributes](
	[ProductId] [int] NOT NULL,
	[AttributeId] [int] NOT NULL,
	[ValueStr] [nvarchar](200) NOT NULL,
 CONSTRAINT [PK_Hishop_ProductAttributes] PRIMARY KEY CLUSTERED 
(
	[ProductId] ASC,
	[AttributeId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[spb_PromotProducts_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[spb_PromotProducts_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spb_PromotProducts_Get] 
	(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalProducts INT

	SET @TotalProducts = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ProductId INT,
        ProductName Nvarchar(200),
        SKU Nvarchar(50),
        AddedDate DateTime,
        SalePrice Money
	)

	INSERT INTO #PageIndexForSearch (ProductId) EXEC sp_executesql @SqlPopulate
	
	SET @TotalProducts = @@ROWCOUNT
	
	SELECT
		p.*
	FROM 
		Hishop_Products p (nolock),
		#PageIndexForSearch
	WHERE 
		p.ProductId = #PageIndexForSearch.ProductId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId

END

IF (@IsCount = 1)
	SELECT @TotalProducts' 
END
GO
/****** Object:  Table [dbo].[Hishop_BrandCategories]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_BrandCategories]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_BrandCategories](
	[BrandId] [int] IDENTITY(1,1) NOT NULL,
	[BrandName] [nvarchar](50) NOT NULL,
	[Logo] [nvarchar](255) NULL,
	[CompanyUrl] [nvarchar](255) NULL,
	[Description] [nvarchar](4000) NULL,
 CONSTRAINT [PK_Hishop_BrandCategories] PRIMARY KEY CLUSTERED 
(
	[BrandId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_OrderItems]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_OrderItems]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_OrderItems](
	[OrderId] [nvarchar](50) NOT NULL,
	[ItemId] [bigint] IDENTITY(1,1) NOT NULL,
	[ProductId] [int] NOT NULL,
	[SKU] [nvarchar](50) NULL,
	[Quantity] [int] NOT NULL,
	[ShipmentQuantity] [int] NOT NULL,
	[CostPrice] [money] NOT NULL,
	[ListPrice] [money] NOT NULL,
	[AdjustedPrice] [money] NOT NULL,
	[ItemListPrice] [money] NOT NULL,
	[ItemAdjustedPrice] [money] NOT NULL,
	[ItemDescription] [nvarchar](200) NOT NULL,
	[ThumbnailsUrl] [nvarchar](255) NULL,
	[Remark] [nvarchar](4000) NULL,
	[Weight] [int] NULL,
 CONSTRAINT [PK_Hishop_OrderItems] PRIMARY KEY CLUSTERED 
(
	[ItemId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_Categories]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Categories]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Categories](
	[CategoryId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[DisplaySequence] [int] NOT NULL,
	[IconUrl] [nvarchar](255) NULL,
	[IndexChar] [char](1) NULL,
	[Meta_Description] [nvarchar](1000) NULL,
	[Meta_Keywords] [nvarchar](1000) NULL,
	[Description] [nvarchar](1000) NULL,
	[Notes] [ntext] NULL,
	[ParentCategoryId] [int] NULL,
	[Depth] [int] NOT NULL,
	[Path] [varchar](4000) NOT NULL,
	[DisplayRecommend] [bit] NOT NULL,
	[DisplayLatest] [bit] NOT NULL,
	[DisplayHotsale] [bit] NOT NULL,
	[DisplaySpecial] [bit] NOT NULL,
	[RewriteName] [nvarchar](50) NULL,
	[TypeId] [int] NULL,
	[Theme] [nvarchar](50) NULL,
 CONSTRAINT [PK_Hishop_Categories] PRIMARY KEY CLUSTERED 
(
	[CategoryId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_Articles]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Articles]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Articles](
	[CategoryId] [int] NOT NULL,
	[ArticleId] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](200) NOT NULL,
	[Description] [nvarchar](1000) NULL,
	[Content] [ntext] NOT NULL,
	[AddedDate] [datetime] NOT NULL,
	[UserId] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_Articles] PRIMARY KEY CLUSTERED 
(
	[ArticleId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_PromoteSales_Present]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PromoteSales_Present]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PromoteSales_Present](
	[ActivityId] [int] NOT NULL,
	[Amount] [money] NOT NULL,
	[PresenteCount] [int] NULL,
 CONSTRAINT [PK_Hishop_PromoteSales_Present] PRIMARY KEY CLUSTERED 
(
	[ActivityId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_Articles_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_Articles_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_Articles_Get]
	(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@CategoryId INT = 0
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalArticles INT

	SET @TotalArticles = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ArticleId INT,
	)
	
	-- 如果指定了文章分类，则搜索文章分类
	IF @CategoryId > 0
	BEGIN
			
		INSERT INTO #PageIndexForSearch (ArticleId) 
		SELECT ArticleId FROM Hishop_Articles WHERE CategoryId = @CategoryId
	END
	ELSE
		INSERT INTO #PageIndexForSearch (ArticleId) SELECT ArticleId FROM Hishop_Articles
	
	SET @TotalArticles = @@ROWCOUNT
	
	SELECT
		a.*
	FROM 
		Hishop_Articles a (nolock),
		#PageIndexForSearch
	WHERE 
		a.ArticleId = #PageIndexForSearch.ArticleId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId

END

IF (@IsCount = 1)
	SELECT @TotalArticles' 
END
GO
/****** Object:  Table [dbo].[Hishop_OrderLookupItems]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_OrderLookupItems]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_OrderLookupItems](
	[LookupListId] [int] NOT NULL,
	[LookupItemId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[IsUserInputRequired] [bit] NOT NULL,
	[UserInputTitle] [nvarchar](20) NULL,
	[AllowInputNothing] [bit] NOT NULL,
	[AppendMoney] [money] NULL,
	[CalculateMode] [int] NULL,
	[Remark] [nvarchar](100) NULL,
 CONSTRAINT [PK_Hishop_OrderLookupItems] PRIMARY KEY CLUSTERED 
(
	[LookupItemId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_PromoteSales_Discount]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PromoteSales_Discount]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PromoteSales_Discount](
	[ActivityId] [int] NOT NULL,
	[Amount] [money] NOT NULL,
	[DiscountValue] [money] NOT NULL,
	[ValueType] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_PromoteSales_Discount] PRIMARY KEY CLUSTERED 
(
	[ActivityId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_ProductBrowseList_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_ProductBrowseList_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_ProductBrowseList_Get]
	(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@UserRank INT = 0,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalProducts INT

	SET @TotalProducts = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex - 1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ProductId INT,
	)
	
	INSERT INTO #PageIndexForSearch (ProductId) EXEC sp_executesql @SqlPopulate
	
	SET @TotalProducts = @@ROWCOUNT
	
	IF @UserRank > 0
		SELECT p.*, ISNULL(pp.SalePrice, p.SalePrice) AS RankPrice FROM  Hishop_Products p  left outer join Hishop_ProductPrices pp ON pp.ProductId = p.ProductId AND pp.RankId = @UserRank, #PageIndexForSearch
		WHERE 
			p.ProductId = #PageIndexForSearch.ProductId AND
			#PageIndexForSearch.IndexId > @PageLowerBound AND
			#PageIndexForSearch.IndexId < @PageUpperBound
		ORDER BY
			#PageIndexForSearch.IndexId
	ELSE
		SELECT p.* , p.SalePrice AS RankPrice FROM  Hishop_Products p, #PageIndexForSearch
		WHERE 
			p.ProductId = #PageIndexForSearch.ProductId AND
			#PageIndexForSearch.IndexId > @PageLowerBound AND
			#PageIndexForSearch.IndexId < @PageUpperBound
		ORDER BY
			#PageIndexForSearch.IndexId
END

IF (@IsCount = 1)
	SELECT @TotalProducts' 
END
GO
/****** Object:  Table [dbo].[Hishop_PriceChangeLogs]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PriceChangeLogs]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PriceChangeLogs](
	[RecordId] [int] IDENTITY(1,1) NOT NULL,
	[OperateDate] [datetime] NOT NULL,
	[CategoryId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[Remark] [nvarchar](4000) NULL,
	[MarketPriceOperate] [nchar](1) NULL,
	[SalePriceOperate] [nchar](1) NULL,
	[CostPriceOperate] [nchar](1) NULL,
	[MarketPrice] [money] NULL,
	[SalePrice] [money] NULL,
	[CostPrice] [money] NULL
)
END
GO
/****** Object:  Table [dbo].[Hishop_OrderLookupLists]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_OrderLookupLists]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_OrderLookupLists](
	[LookupListId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[SelectMode] [int] NOT NULL,
	[Description] [nvarchar](4000) NULL,
 CONSTRAINT [PK_Hishop_OrderLookupLists] PRIMARY KEY CLUSTERED 
(
	[LookupListId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_ReceivedMessages]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ReceivedMessages]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ReceivedMessages](
	[ReceiveMessageId] [bigint] IDENTITY(1,1) NOT NULL,
	[AddresserId] [int] NOT NULL,
	[AddresseeId] [int] NOT NULL,
	[Title] [nvarchar](100) NOT NULL,
	[PublishContent] [nvarchar](3000) NOT NULL,
	[PublishDate] [datetime] NOT NULL,
	[LastTime] [datetime] NOT NULL,
	[IsRead] [bit] NOT NULL,
 CONSTRAINT [PK_Hishop_ReceivedMessages] PRIMARY KEY CLUSTERED 
(
	[ReceiveMessageId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_SendedMessages]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_SendedMessages]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_SendedMessages](
	[SendMessageId] [bigint] IDENTITY(1,1) NOT NULL,
	[AddresserId] [int] NOT NULL,
	[AddresseeId] [int] NOT NULL,
	[Title] [nvarchar](100) NOT NULL,
	[PublishContent] [nvarchar](3000) NOT NULL,
	[PublishDate] [datetime] NOT NULL,
	[ReceiveMessageId] [bigint] NULL,
 CONSTRAINT [PK_Hishop_SendedMessages] PRIMARY KEY CLUSTERED 
(
	[SendMessageId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_ShippingTypeGroups]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ShippingTypeGroups]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ShippingTypeGroups](
	[GroupId] [int] IDENTITY(1,1) NOT NULL,
	[ModeId] [int] NOT NULL,
	[Price] [money] NOT NULL,
	[AddPrice] [money] NULL,
 CONSTRAINT [PK_Hishop_ShippingTypeGroups] PRIMARY KEY CLUSTERED 
(
	[GroupId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_RefundOrders]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_RefundOrders]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_RefundOrders](
	[OrderId] [nvarchar](50) NOT NULL,
	[IsOrderRefund] [bit] NOT NULL,
	[TotalBalance] [money] NULL,
	[Remark] [nvarchar](4000) NULL,
 CONSTRAINT [PK_Hishop_RefundOrders] PRIMARY KEY CLUSTERED 
(
	[OrderId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_ReceivedMessages_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_ReceivedMessages_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_ReceivedMessages_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@Total int = 0 output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex - 1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForSearch
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ReceiveMessageId BIGINT
	)

	INSERT INTO #PageIndexForSearch (ReceiveMessageId) 
    Exec sp_executesql @sqlPopulate
    
    SET @Total = @@rowcount
    
	SELECT m.*,
	       #PageIndexForSearch.IndexId as Id,
	       (select UserName from vw_Users_FullUser where hi_userId=m.AddresserId) as Addresser,
	       (select UserName from vw_Users_FullUser where hi_userId=m.AddresseeId) as Addressee
	FROM 
	 Hishop_ReceivedMessages m ,#PageIndexForSearch
	WHERE 
		m.ReceiveMessageId = #PageIndexForSearch.ReceiveMessageId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_SendedMessages_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_SendedMessages_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_SendedMessages_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@Total int = 0 output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex - 1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForSearch
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		SendMessageId BIGINT
	)

	INSERT INTO #PageIndexForSearch (SendMessageId) 
    Exec sp_executesql @sqlPopulate
    
    SET @Total = @@rowcount
    
	SELECT m.*,
	       #PageIndexForSearch.IndexId as Id,
	       (select UserName from vw_Users_FullUser where hi_userId=m.AddresserId) as Addresser,
	       (select UserName from vw_Users_FullUser where hi_userId=m.AddresseeId) as Addressee
	FROM 
	 Hishop_SendedMessages m ,#PageIndexForSearch
	WHERE 
		m.SendMessageId = #PageIndexForSearch.SendMessageId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId

END' 
END
GO
/****** Object:  Table [dbo].[Hishop_ShippingTypes]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ShippingTypes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ShippingTypes](
	[ModeId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[Weight] [int] NOT NULL,
	[AddWeight] [int] NULL,
	[Price] [money] NOT NULL,
	[AddPrice] [money] NULL,
	[Description] [nvarchar](4000) NULL,
	[DisplaySequence] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_ShippingTypes] PRIMARY KEY CLUSTERED 
(
	[ModeId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_PaymentTypes]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PaymentTypes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PaymentTypes](
	[ModeId] [int] IDENTITY(1,1) NOT NULL,
	[MerchantCode] [nvarchar](300) NOT NULL,
	[EmailAddress] [nvarchar](255) NULL,
	[SecretKey] [nvarchar](4000) NULL,
	[SecondKey] [nvarchar](4000) NULL,
	[Password] [nvarchar](4000) NULL,
	[Partner] [nvarchar](300) NULL,
	[Name] [nvarchar](100) NOT NULL,
	[Description] [ntext] NULL,
	[Gateway] [nvarchar](200) NULL,
	[DisplaySequence] [int] NOT NULL,
	[Charge] [money] NOT NULL,
	[IsPercent] [bit] NOT NULL,
	[Logo] [nvarchar](255) NULL,
 CONSTRAINT [PK_Hishop_PaymentTypes] PRIMARY KEY CLUSTERED 
(
	[ModeId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_Regions]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Regions]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Regions](
	[AreaId] [int] NULL,
	[RegionId] [int] IDENTITY(100,1) NOT NULL,
	[ParentId] [int] NULL,
	[RegionName] [nvarchar](100) NOT NULL,
	[DisplaySequence] [int] NOT NULL,
	[Path] [varchar](4000) NOT NULL,
	[Depth] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_Regions] PRIMARY KEY CLUSTERED 
(
	[RegionId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_OrderItemStatistics_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_OrderItemStatistics_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_OrderItemStatistics_Get]
(
	@PageIndex int,
	@PageSize int,
	@sqlPopulate ntext,
	@TotalProductSales int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForProductSales
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		ItemId int,
		OrderDate datetime
	)	

	INSERT INTO #PageIndexForProductSales(ItemId,OrderDate)
	Exec sp_executesql @sqlPopulate

	SET @TotalProductSales = @@rowcount
	
	SELECT 
		o.*, 
		(select ProductName from Hishop_Products where ProductId=o.ProductId) as ProductName,
		(select orderDate from Hishop_orders where orderid=o.orderid) as orderDate
	FROM   Hishop_OrderItems o, #PageIndexForProductSales S
	WHERE 
			o.ItemId = S.ItemId AND
			S.IndexId > @PageLowerBound AND
			S.IndexId < @PageUpperBound 
	ORDER BY S.IndexId
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_OrderGifts]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_OrderGifts]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_OrderGifts](
	[OrderId] [nvarchar](50) NOT NULL,
	[GiftId] [int] NOT NULL,
	[GiftName] [nvarchar](100) NOT NULL,
	[CostPrice] [money] NULL,
	[AdjustedPrice] [money] NULL,
	[Weight] [int] NULL,
 CONSTRAINT [PK_Hishop_OrderGifts] PRIMARY KEY CLUSTERED 
(
	[OrderId] ASC,
	[GiftId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_OrderItemStatisticsNoPage_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_OrderItemStatisticsNoPage_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_OrderItemStatisticsNoPage_Get]
(
	@sqlPopulate ntext,
	@TotalProductSales int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN

	CREATE TABLE #PageIndexForProductSales
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		ItemId int,
		OrderDate datetime
	)	

	INSERT INTO #PageIndexForProductSales(ItemId,OrderDate)
	Exec sp_executesql @sqlPopulate

	SET @TotalProductSales = @@rowcount
	
	SELECT 
		o.*, 
		(select ProductName from Hishop_Products where ProductId=o.ProductId) as ProductName,
		(select orderDate from Hishop_orders where orderid=o.orderid) as orderDate
	FROM   Hishop_OrderItems o, #PageIndexForProductSales S
	WHERE 
			o.ItemId = S.ItemId
	ORDER BY S.IndexId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_MainRegions_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_MainRegions_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_MainRegions_Get]
	@PageIndex   INT,
	@PageSize	 INT,
	@IsCount	 BIT
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn	INT
	DECLARE @TotalRecords	INT

	SET @TotalRecords = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		RegionId INT,
	)
	
	INSERT INTO #PageIndexForSearch (RegionId)
	SELECT RegionId FROM Hishop_Regions WHERE ParentId IS NULL ORDER BY DisplaySequence
	
	SET @TotalRecords = @@ROWCOUNT
	
		SELECT
		r.*
	FROM 
		Hishop_Regions r (nolock),
		#PageIndexForSearch
	WHERE 
		r.RegionId = #PageIndexForSearch.RegionId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId
		
	SELECT @TotalRecords
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_BalanceDetailsNoPage_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_BalanceDetailsNoPage_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_BalanceDetailsNoPage_Get]
(
	@IsCount bit,
	@SqlPopulate ntext
)

AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN 

	DECLARE @TotalBalanceDetails int
	SET @TotalBalanceDetails = 0 

	CREATE TABLE #PageIndexForBalanceDetails
	(
		IndexId int IDENTITY(1,1) NOT NULL,                                                          
		JournalNumber bigint
	)

	INSERT INTO #PageIndexForBalanceDetails(JournalNumber)
	EXEC sp_executesql @SqlPopulate

	SET @TotalBalanceDetails = @@rowcount
	
	SELECT 
		B.JournalNumber,B.UserId,B.TradeDate,B.TradeType,B.Income,B.Expenses,B.Balance,B.Remark,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = B.Payer) AS PayerName,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = B.Payee) AS PayeeName,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = B.UserId) AS UserName
	FROM
		Hishop_BalanceDetails B ,
		#PageIndexForBalanceDetails			
	WHERE
		B.JournalNumber = #PageIndexForBalanceDetails.JournalNumber
	ORDER BY 
		#PageIndexForBalanceDetails.IndexId	
END

--Return the record count
IF (@IsCount = 1)
	SELECT @TotalBalanceDetails' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_ProductPrices_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_ProductPrices_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_ProductPrices_Get]
	(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@RankId INT,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalProducts INT

	SET @TotalProducts = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ProductId INT
	)
	

	INSERT INTO #PageIndexForSearch (ProductId) EXEC sp_executesql @SqlPopulate
	
	SET @TotalProducts = @@ROWCOUNT	
		
	BEGIN
		SELECT
			p.*,(SELECT ISNULL(SalePrice, p.SalePrice) FROM Hishop_ProductPrices WHERE ProductId=p.ProductId AND RankId=@RankId) AS RankPrice,
			((SELECT ISNULL(SalePrice, p.SalePrice) FROM Hishop_ProductPrices WHERE ProductId=p.ProductId AND RankId=@RankId) 
				- p.CostPrice) AS Profit  
		FROM 			
			Hishop_Products p(nolock) inner join #PageIndexForSearch	on p.ProductId = #PageIndexForSearch.ProductId 
		WHERE
			#PageIndexForSearch.IndexId > @PageLowerBound AND
			#PageIndexForSearch.IndexId < @PageUpperBound
		ORDER BY
			#PageIndexForSearch.IndexId
	END

IF (@IsCount = 1)
	SELECT @TotalProducts
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_BalanceDrawRequestsNoPage_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_BalanceDrawRequestsNoPage_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_BalanceDrawRequestsNoPage_Get]
(
	@IsCount bit,
	@SqlPopulate ntext
)

AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN 
	DECLARE @TotalBalanceDrawRequest int
	SET @TotalBalanceDrawRequest = 0 

	CREATE TABLE #PageIndexForBalanceDrawRequest
	(
		IndexId int IDENTITY(1,1) NOT NULL,
		JournalNumber bigint
	)

	INSERT INTO #PageIndexForBalanceDrawRequest(JournalNumber)
	EXEC sp_executesql @SqlPopulate

	SET @TotalBalanceDrawRequest = @@rowcount
	
	SELECT 
		B.*,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = B.Applicant) AS UserName		
	FROM
		Hishop_BalanceDrawRequest B (nolock),	
		#PageIndexForBalanceDrawRequest	
	WHERE
		B.JournalNumber = #PageIndexForBalanceDrawRequest.JournalNumber
	ORDER BY 
		#PageIndexForBalanceDrawRequest.IndexId	
END

--Return the record count
IF (@IsCount = 1)
	SELECT @TotalBalanceDrawRequest' 
END
GO
/****** Object:  Table [dbo].[Hishop_Orders]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Orders]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Orders](
	[OrderId] [nvarchar](50) NOT NULL,
	[OrderDate] [datetime] NOT NULL,
	[UserId] [int] NOT NULL,
	[Username] [nvarchar](64) NOT NULL,
	[EmailAddress] [nvarchar](255) NULL,
	[Remark] [nvarchar](4000) NULL,
	[AdjustedDiscount] [money] NULL,
	[ActivityStatus] [int] NULL,
	[IsPOD] [bit] NULL,
	[ShippingRegion] [nvarchar](300) NULL,
	[Address] [nvarchar](300) NULL,
	[ZipCode] [nvarchar](20) NULL,
	[ShipTo] [nvarchar](50) NULL,
	[TelPhone] [nvarchar](50) NULL,
	[CellPhone] [nvarchar](50) NULL,
	[ShippingModeId] [int] NULL,
	[ModeName] [nvarchar](50) NULL,
	[RegionId] [int] NULL,
	[Freight] [money] NULL,
	[AdjustedFreight] [money] NULL,
	[ShipOrderNumber] [nvarchar](50) NULL,
	[Weight] [int] NULL,
	[ShippingStatus] [int] NULL,
	[PaymentGateway] [nvarchar](50) NULL,
	[PaymentType] [nvarchar](100) NULL,
	[CurrencyCode] [nvarchar](20) NULL,
	[CurrencyName] [nvarchar](20) NULL,
	[PayCharge] [money] NULL,
	[AdjustedPayCharge] [money] NULL,
	[RefundStatus] [int] NULL,
	[PaymentStatus] [int] NULL,
	[OrderTotal] [money] NULL,
	[OrderCostPrice] [money] NULL,
	[OrderProfit] [money] NULL,
	[ActualFreight] [money] NULL,
	[OtherCost] [money] NULL,
	[OptionPrice] [money] NULL,
	[Amount] [money] NULL,
	[ActivityName] [nvarchar](100) NULL,
	[FeeFreeAmount] [money] NULL,
	[EightFree] [bit] NULL,
	[ProcedureFeeFree] [bit] NULL,
	[OrderOptionFree] [bit] NULL,
	[DiscountName] [nvarchar](100) NULL,
	[DiscountAmount] [money] NULL,
	[DiscountValue] [money] NULL,
	[DiscountValueType] [int] NULL,
	[CouponName] [nvarchar](100) NULL,
	[CouponCode] [nvarchar](50) NULL,
	[CouponAmount] [money] NULL,
	[CouponValue] [money] NULL,
 CONSTRAINT [PK_Hishop_Orders] PRIMARY KEY CLUSTERED 
(
	[OrderId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ca_PromoteGifts_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ca_PromoteGifts_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ca_PromoteGifts_Get] 
	(
		@PageIndex INT,
		@PageSize INT,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalPromoteGifts INT

	SET @TotalPromoteGifts = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ActivityId INT,
		GiftId INT
	)

	INSERT INTO #PageIndexForSearch (ActivityId, GiftId) EXEC (@SqlPopulate)
	
	SET @TotalPromoteGifts = @@ROWCOUNT
	
	SELECT
		#PageIndexForSearch.ActivityId, g.*
	FROM 
		Hishop_Gifts g (nolock),
		#PageIndexForSearch
	WHERE 
		g.GiftId = #PageIndexForSearch.GiftId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId

END

SELECT @TotalPromoteGifts' 
END
GO
/****** Object:  Table [dbo].[Hishop_ShippingRegions]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ShippingRegions]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ShippingRegions](
	[ModeId] [int] NOT NULL,
	[GroupId] [int] NOT NULL,
	[RegionId] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_ShippingRegions] PRIMARY KEY CLUSTERED 
(
	[ModeId] ASC,
	[RegionId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_Products_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_Products_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_Products_Get]
	(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalProducts INT

	SET @TotalProducts = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex - 1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ProductId INT,
	)
	
	INSERT INTO #PageIndexForSearch (ProductId) EXEC sp_executesql @SqlPopulate
	
	SET @TotalProducts = @@ROWCOUNT
	
	SELECT
		p.*, (SELECT COUNT(ProductId) FROM Hishop_ProductReviews WHERE ProductId = p.ProductId) AS TotalReview
	FROM 
		Hishop_Products p (nolock),
		#PageIndexForSearch
	WHERE 
		p.ProductId = #PageIndexForSearch.ProductId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId
END

IF (@IsCount = 1)
	SELECT @TotalProducts' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_DisplaceCategory]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_DisplaceCategory]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_DisplaceCategory]
	@fromCategoryId int, 
	@toCategory int
AS
	UPDATE Hishop_Products
	SET CategoryId=@toCategory
	WHERE CategoryId=@fromCategoryId
RETURN 0' 
END
GO
/****** Object:  Table [dbo].[Hishop_Currencys]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Currencys]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Currencys](
	[Code] [nvarchar](20) NOT NULL,
	[Name] [nvarchar](20) NOT NULL,
	[Symbol] [nvarchar](20) NOT NULL,
	[ExchangeRate] [money] NOT NULL,
 CONSTRAINT [PK_Hishop_Currencys] PRIMARY KEY CLUSTERED 
(
	[Code] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ca_PromoteProducts_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ca_PromoteProducts_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ca_PromoteProducts_Get] 
	(
		@PageIndex INT,
		@PageSize INT,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalPromoteProducts INT

	SET @TotalPromoteProducts = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ActivityId INT,
		ProductId INT
	)

	INSERT INTO #PageIndexForSearch (ActivityId, ProductId) EXEC (@SqlPopulate)
	
	SET @TotalPromoteProducts = @@ROWCOUNT
	
	SELECT
		#PageIndexForSearch.ActivityId, p.*
	FROM 
		Hishop_Products p (nolock),
		#PageIndexForSearch
	WHERE 
		p.ProductId = #PageIndexForSearch.ProductId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId

END

SELECT @TotalPromoteProducts' 
END
GO
/****** Object:  Table [dbo].[Hishop_Groupbuying]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Groupbuying]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Groupbuying](
	[GroupbuyId] [int] NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[Description] [ntext] NULL,
	[ThumbnailsUrl] [nvarchar](255) NULL,
	[InFocusImageUrl] [nvarchar](255) NULL,
	[SalePrice] [money] NOT NULL,
	[OriginalPrice] [money] NOT NULL,
	[Stock] [int] NULL,
	[Weight] [int] NULL,
	[StartTime] [datetime] NOT NULL,
	[ClosingTime] [datetime] NOT NULL,
	[CostPrice] [money] NULL,
	[Condition] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_Groupbuying] PRIMARY KEY CLUSTERED 
(
	[GroupbuyId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_Favorites_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_Favorites_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_Favorites_Get]
	(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
    @UserId INT = 0,
	@TotalFavorites int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForFavorites
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		FavoriteId int
	)	

	INSERT INTO #PageIndexForFavorites(FavoriteId)
	Exec sp_executesql @sqlPopulate

	SET @TotalFavorites = @@rowcount

	SELECT
		F.FavoriteId, F.ProductId, F.UserId, F.Tags, F.Remark,
         P.Stock, P.ProductName, P.MarketPrice,
        P.SalePrice, P.ShortDescription, P.ThumbnailsUrl
	FROM 
		Hishop_Products P,
		Hishop_Favorite F (nolock),	
		#PageIndexForFavorites
	WHERE 
		F.ProductId = P.ProductId AND
		F.FavoriteId = #PageIndexForFavorites.FavoriteId AND
		#PageIndexForFavorites.IndexId > @PageLowerBound AND
		#PageIndexForFavorites.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForFavorites.IndexId

END

IF (@IsCount = 1)
	SELECT @TotalFavorites' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_Attributes_GetAllByType]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_Attributes_GetAllByType]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_Attributes_GetAllByType]
(
	@TypeId INT
)
AS

	CREATE TABLE #Attributes(AttributeId INT)
	
	INSERT INTO #Attributes SELECT AttributeId FROM Hishop_Attributes WHERE TypeId = @TypeId AND UsageMode <> 2
	
	SELECT ha.* FROM Hishop_Attributes ha INNER JOIN #Attributes ON ha.AttributeId = #Attributes.AttributeId
	SELECT * FROM Hishop_AttributeValues v INNER JOIN #Attributes ON v.AttributeId = #Attributes.AttributeId
	
	DROP TABLE #Attributes' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_SpecFields_GetAllByType]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_SpecFields_GetAllByType]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_SpecFields_GetAllByType]
(
	@TypeId INT
)
AS

	CREATE TABLE #Attributes(AttributeId INT)
	
	INSERT INTO #Attributes SELECT AttributeId FROM Hishop_Attributes WHERE TypeId = @TypeId AND UsageMode = 2
	
	SELECT ha.* FROM Hishop_Attributes ha INNER JOIN #Attributes ON ha.AttributeId = #Attributes.AttributeId
	SELECT * FROM Hishop_AttributeValues v INNER JOIN #Attributes ON v.AttributeId = #Attributes.AttributeId
	
	DROP TABLE #Attributes' 
END
GO
/****** Object:  Table [dbo].[Hishop_GroupbuyingHistorys]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_GroupbuyingHistorys]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_GroupbuyingHistorys](
	[GroupbuyId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[Quantity] [int] NOT NULL,
	[Price] [money] NOT NULL,
	[GroupbuyingStatus] [int] NULL,
	[TradeTime] [datetime] NOT NULL
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Order_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Order_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[sp_Order_Get]
(
@OrderId nvarchar(50)
)
as
	SELECT o.* FROM Hishop_Orders o Where o.OrderId = @OrderId' 
END
GO
/****** Object:  Table [dbo].[Hishop_ArticleCategories]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ArticleCategories]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ArticleCategories](
	[CategoryId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[DisplaySequence] [int] NOT NULL,
	[IconUrl] [nvarchar](255) NULL,
	[Description] [nvarchar](1000) NULL,
 CONSTRAINT [PK_Hishop_ArticleCategories] PRIMARY KEY CLUSTERED 
(
	[CategoryId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_PackageSales]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PackageSales]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PackageSales](
	[PackageId] [int] NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[Stock] [int] NULL,
	[Upselling] [bit] NOT NULL,
	[Weight] [int] NULL,
	[SalePrice] [money] NOT NULL,
	[DisplaySequence] [int] NOT NULL,
	[OriginalPrice] [money] NOT NULL,
 CONSTRAINT [PK_Hishop_PackageSales] PRIMARY KEY CLUSTERED 
(
	[PackageId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_Article_Search]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_Article_Search]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_Article_Search] 
	@PageIndex   INT,
	@PageSize	 INT,
	@IsCount	 BIT,
	@Keywords	 NVARCHAR(100)= null,
    @CategoryId  INT		   = null,
	@StartArticleTime NVARCHAR(100)  = null,
	@EndArticleTime NVARCHAR(100)    = null,
	@SortBy		 NVARCHAR(100),
	@SortOrder   NVARCHAR(100)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn	INT
	DECLARE @TotalRecords	INT
    DECLARE @Sql			NVARCHAR(4000)
	
	SET @Sql=''SELECT ArticleId FROM Hishop_Articles WHERE 1 = 1''
	SET @TotalRecords = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	IF @Keywords is not null
		SET @Sql=@Sql+'' AND (LOWER(Title) like ''''%''+@Keywords+''%'''' OR LOWER(Description) like ''''%''+@Keywords+''%'''')''
    IF @CategoryId > 0
		SET @Sql=@Sql+'' AND CategoryId = ''+str(@CategoryId)
    IF @StartArticleTime is not null
		SET @Sql=@Sql+'' AND AddedDate >=''''''+@StartArticleTime+''''''''
	IF @EndArticleTime is not null
		SET @Sql=@Sql+'' AND AddedDate <=''''''+@EndArticleTime+''''''''
	SET @Sql=@Sql+'' ORDER BY ''+@SortBy+ '' ''+ @SortOrder

	print @Sql
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ArticleId INT,
	)
	
	INSERT INTO #PageIndexForSearch (ArticleId)
	Exec(@Sql)
	
	SET @TotalRecords = @@ROWCOUNT
	
		SELECT
		pm.*,pc.[Name]
	FROM 
		Hishop_Articles pm (nolock),
		#PageIndexForSearch,
        Hishop_ArticleCategories PC
	WHERE 
		pm.ArticleId = #PageIndexForSearch.ArticleId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound AND
		pm.CategoryId=pc.CategoryId
	ORDER BY
		#PageIndexForSearch.IndexId
		
	SELECT @TotalRecords
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_Panicbuying]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Panicbuying]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Panicbuying](
	[PanicbuyingId] [int] NOT NULL,
	[StartTime] [datetime] NOT NULL,
	[ClosingTime] [datetime] NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[Description] [ntext] NULL,
	[ThumbnailsUrl] [nvarchar](255) NULL,
	[InFocusImageUrl] [nvarchar](255) NULL,
	[SalePrice] [money] NOT NULL,
	[OriginalPrice] [money] NOT NULL,
	[Stock] [int] NULL,
	[Weight] [int] NULL,
	[CostPrice] [money] NULL,
 CONSTRAINT [PK_Hishop_Panicbuying] PRIMARY KEY CLUSTERED 
(
	[PanicbuyingId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_Products]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Products]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Products](
	[CategoryId] [int] NOT NULL,
	[TypeId] [int] NULL,
	[ProductId] [int] IDENTITY(1,1) NOT NULL,
	[BrandId] [int] NULL,
	[SKU] [nvarchar](50) NULL,
	[SupplierId] [int] NULL,
	[ProductName] [nvarchar](200) NOT NULL,
	[ShortDescription] [nvarchar](2000) NULL,
	[Unit] [nvarchar](50) NULL,
	[Weight] [int] NULL,
	[Description] [ntext] NULL,
	[Title] [nvarchar](100) NULL,
	[Meta_Description] [nvarchar](1000) NULL,
	[Meta_Keywords] [nvarchar](1000) NULL,
	[ThumbnailsUrl] [nvarchar](255) NULL,
	[InFocusImageUrl] [nvarchar](255) NULL,
	[Recommended] [bit] NOT NULL,
	[Latest] [bit] NOT NULL,
	[Hotsale] [bit] NOT NULL,
	[SpecialOffer] [bit] NOT NULL,
	[CostPrice] [money] NULL,
	[MarketPrice] [money] NULL,
	[Upselling] [bit] NOT NULL,
	[SalePrice] [money] NOT NULL,
	[Stock] [int] NULL,
	[QuantityLimit] [int] NULL,
	[MinQuantity] [int] NULL,
	[AddedDate] [datetime] NOT NULL,
	[VistiCounts] [int] NOT NULL,
	[DisplaySequence] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_Products] PRIMARY KEY CLUSTERED 
(
	[ProductId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_PackageItems]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PackageItems]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PackageItems](
	[PackageId] [int] NOT NULL,
	[ProductId] [int] NOT NULL,
	[SKU] [nvarchar](50) NOT NULL,
	[Quantity] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_PackageItems] PRIMARY KEY CLUSTERED 
(
	[PackageId] ASC,
	[ProductId] ASC,
	[SKU] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_RegisterMemberRank_Set]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_RegisterMemberRank_Set]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_RegisterMemberRank_Set]
	@UserId int = 0, 
	@UserRank int
AS
	Update Hishop_UserProfile set UserRank = @UserRank WHERE UserId = @UserId' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_OrderCartItem_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_OrderCartItem_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_OrderCartItem_Get]
(
 	@PageIndex   INT,
	@PageSize	 INT,
	@IsCount	 BIT,
    @SqlPopulate     NTEXT
    
)
as
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn	INT
	DECLARE @TotalRecords	INT
   
	SET @TotalRecords = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ItemId INT,
	)
	
	INSERT INTO #PageIndexForSearch (ItemId)
	Exec sp_executesql @SqlPopulate
	SET @TotalRecords = @@rowcount
	
	 SELECT
		o.*
	FROM 
		Hishop_OrderItems o (nolock),
		#PageIndexForSearch
	WHERE 
		o.ItemId = #PageIndexForSearch.ItemId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
        
	ORDER BY
		#PageIndexForSearch.IndexId
END
	SELECT @TotalRecords' 
END
GO
/****** Object:  Table [dbo].[Hishop_PrivilegeInRoles]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PrivilegeInRoles]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PrivilegeInRoles](
	[RoleId] [uniqueidentifier] NOT NULL,
	[ResourceId] [int] NOT NULL,
	[OperationId] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_PrivilegeInRoles] PRIMARY KEY CLUSTERED 
(
	[RoleId] ASC,
	[ResourceId] ASC,
	[OperationId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_ProductTypes]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ProductTypes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ProductTypes](
	[TypeId] [int] IDENTITY(1,1) NOT NULL,
	[TypeName] [nvarchar](50) NOT NULL,
	[Remark] [nvarchar](200) NULL,
 CONSTRAINT [PK_Hishop_ProductTypes] PRIMARY KEY CLUSTERED 
(
	[TypeId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[spb_ProductStock_Update]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[spb_ProductStock_Update]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spb_ProductStock_Update]
(
 @ProductId INT,
 @Stock INT =null
)
as
 IF @Stock IS NULL
 BEGIN
  Update Hishop_Products Set Stock =NULL Where ProductId =@ProductId
  return
 END 
 
 IF @Stock = 0
 BEGIN
  Update Hishop_Products Set Stock =0 , UpSelling= 0 Where ProductId =@ProductId
  RETURN
 END
 ELSE
 BEGIN
   Update Hishop_Products Set Stock =@Stock Where ProductId =@ProductId
 END' 
END
GO
/****** Object:  Table [dbo].[Hishop_Votes]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Votes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Votes](
	[voteId] [bigint] IDENTITY(1,1) NOT NULL,
	[VoteName] [nvarchar](100) NOT NULL,
	[IsBackup] [bit] NOT NULL,
	[MaxCheck] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_Votes] PRIMARY KEY CLUSTERED 
(
	[voteId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_ProductTypes_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_ProductTypes_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_ProductTypes_Get]
	(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalProductTypes INT

	SET @TotalProductTypes = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		TypeId INT,
	)
	
	INSERT INTO #PageIndexForSearch (TypeId) EXEC sp_executesql @SqlPopulate
	
	SET @TotalProductTypes = @@ROWCOUNT	
		
	BEGIN
		SELECT Hishop_ProductTypes.*
		FROM 			
			Hishop_ProductTypes inner join #PageIndexForSearch	on Hishop_ProductTypes.TypeId = #PageIndexForSearch.TypeId 
		WHERE
			#PageIndexForSearch.IndexId > @PageLowerBound AND
			#PageIndexForSearch.IndexId < @PageUpperBound
		ORDER BY
			#PageIndexForSearch.IndexId
	END

IF (@IsCount = 1)
	SELECT @TotalProductTypes
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_Favorite]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Favorite]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Favorite](
	[FavoriteId] [int] IDENTITY(1,1) NOT NULL,
	[ProductId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[Tags] [nvarchar](100) NOT NULL,
	[Remark] [nvarchar](500) NULL,
 CONSTRAINT [PK_Hishop_Favorite] PRIMARY KEY CLUSTERED 
(
	[ProductId] ASC,
	[UserId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ProductsNoPage_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ProductsNoPage_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ProductsNoPage_Get] 
		(
		@IsCount BIT,
		@CategoryId INT = 0,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @TotalProducts INT

	SET @TotalProducts = 0


	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ProductId INT,
        ProductName Nvarchar(200),
        SKU Nvarchar(50),
        AddedDate DateTime,
        SalePrice Money,
        Stock INT,
        Recommended BIT,
        Latest BIT,
        Hotsale BIT,
        SpecialOffer BIT,
        VistiCounts INT,
        ReviewCounts INT
	)
	
	-- 如果指定了商品分类，则搜索商品分类
	IF @CategoryId > 0
	BEGIN
		-- 匹配当前分类的Path
		DECLARE @Path VARCHAR(4000)
		DECLARE @ParmDefinition NVARCHAR(500)
		
		SELECT 
			@ParmDefinition = N''@CategoryId INT,@Path VARCHAR(4000)'', @Path = Path + LTRIM(RTRIM(STR(@CategoryId))) + '','' 
		FROM 
			Hishop_Categories 
		WHERE 
			CategoryId = @CategoryId
			
		INSERT INTO #PageIndexForSearch (ProductId,ProductName,SKU,AddedDate,SalePrice,Stock, Recommended, Latest, Hotsale, SpecialOffer, VistiCounts, ReviewCounts) 
		EXEC sp_executesql @SqlPopulate, @ParmDefinition, @CategoryId, @Path		
	END
	ELSE
		INSERT INTO #PageIndexForSearch (ProductId,ProductName,SKU,AddedDate,SalePrice,Stock, Recommended, Latest, Hotsale, SpecialOffer, VistiCounts, ReviewCounts)   EXEC sp_executesql @SqlPopulate
	
	SET @TotalProducts = @@ROWCOUNT
	
	SELECT
	  p.[CategoryId]
      ,p.[ProductId]
      ,p.[BrandId]
      ,p.[SKU]
      ,p.[SupplierId]
      ,p.[ProductName]
      ,p.[ShortDescription]
      ,p.[Unit]
      ,p.[Weight]
      ,p.[Description]
      ,p.[Title]
      ,p.[Meta_Description]
      ,p.[Meta_Keywords]
      ,p.[ThumbnailsUrl]
      ,p.[InFocusImageUrl]
      ,p.[Recommended]
      ,p.[Latest]
      ,p.[Hotsale]
      ,p.[SpecialOffer]
      ,p.[CostPrice]
      ,p.[MarketPrice]
      ,p.[Upselling]
      ,p.[SalePrice]
      ,p.[Stock]
      ,p.[QuantityLimit]
      ,p.[AddedDate]
      ,p.[VistiCounts]
	FROM 
		Hishop_Products p (nolock),
		#PageIndexForSearch
	WHERE 
		p.ProductId = #PageIndexForSearch.ProductId 
	ORDER BY
		#PageIndexForSearch.IndexId

END

IF (@IsCount = 1)
	SELECT @TotalProducts' 
END
GO
/****** Object:  Table [dbo].[Hishop_UserRanks]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_UserRanks]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_UserRanks](
	[RankId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[Description] [nvarchar](200) NULL,
	[Point] [int] NULL,
	[IsDefault] [bit] NOT NULL,
	[IsAgentRank] [bit] NOT NULL,
	[NumberOfMemberRanks] [int] NULL,
	[IsMemberCreated] [bit] NOT NULL,
	[CreatorUserId] [int] NULL,
	[PriceType] [nvarchar](20) NOT NULL,
	[PriceOperations] [nvarchar](10) NOT NULL,
	[PriceValue] [money] NOT NULL,
 CONSTRAINT [PK_Hishop_UserRanks] PRIMARY KEY CLUSTERED 
(
	[RankId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_PromoteSales]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PromoteSales]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PromoteSales](
	[ActivityId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[PromoteType] [int] NOT NULL,
	[Description] [ntext] NULL,
	[StartTime] [datetime] NOT NULL,
	[ClosingTime] [datetime] NOT NULL,
 CONSTRAINT [PK_Hishop_PromoteSales] PRIMARY KEY CLUSTERED 
(
	[ActivityId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_VoteItems]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_VoteItems]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_VoteItems](
	[voteId] [bigint] NOT NULL,
	[VoteItemId] [bigint] IDENTITY(1,1) NOT NULL,
	[VoteItemName] [nvarchar](100) NOT NULL,
	[ItemCount] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_VoteItems] PRIMARY KEY CLUSTERED 
(
	[VoteItemId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ca_Gifts_Search]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ca_Gifts_Search]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ca_Gifts_Search] 
	(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalProducts INT

	SET @TotalProducts = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		GiftId INT,
	)

	INSERT INTO #PageIndexForSearch (GiftId) EXEC (@SqlPopulate)
	
	SET @TotalProducts = @@ROWCOUNT
	
	SELECT
		g.*
	FROM 
		Hishop_Gifts g (nolock),
		#PageIndexForSearch
	WHERE 
		g.GiftId = #PageIndexForSearch.GiftId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId

END

IF (@IsCount = 1)
	SELECT @TotalProducts' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_SearchCategoriesNoPage_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_SearchCategoriesNoPage_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_SearchCategoriesNoPage_Get] 
		(
		@CategoryId INT = 0,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		CategoryId INT,
	)
	
	INSERT INTO #PageIndexForSearch (CategoryId)   EXEC sp_executesql @SqlPopulate
	
	
	SELECT C.*
	FROM 
		Hishop_Categories C (nolock),
		#PageIndexForSearch S
	WHERE 
		C.CategoryId = S.CategoryId
	ORDER BY
		S.IndexId

END' 
END
GO
/****** Object:  Table [dbo].[Hishop_ProductAccessories]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ProductAccessories]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ProductAccessories](
	[ProductId] [int] NOT NULL,
	[ProductAccessoriesId] [int] NOT NULL,
	[ProductAccessoriesSKU] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_Hishop_ProductAccessories] PRIMARY KEY CLUSTERED 
(
	[ProductId] ASC,
	[ProductAccessoriesSKU] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ca_Promotes_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ca_Promotes_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ca_Promotes_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@TotalPromotes int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForPromotes
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		ActivityId int
	)	

	INSERT INTO #PageIndexForPromotes(ActivityId)
	Exec sp_executesql @sqlPopulate

	SET @TotalPromotes = @@rowcount
	
	SELECT Hishop_PromoteSales.*
	FROM Hishop_PromoteSales, #PageIndexForPromotes
	WHERE 
		Hishop_PromoteSales.ActivityId = #PageIndexForPromotes.ActivityId AND
		#PageIndexForPromotes.IndexId > @PageLowerBound AND
		#PageIndexForPromotes.IndexId < @PageUpperBound 
	ORDER BY #PageIndexForPromotes.IndexId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_Votes_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_Votes_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_Votes_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@TotalVotes int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForVotes
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		VoteId int
	)	

	INSERT INTO #PageIndexForVotes(VoteId)
	Exec sp_executesql @sqlPopulate

	SET @TotalVotes = @@rowcount
	
	SELECT Hishop_Votes.*,
		   (SELECT SUM(ItemCount) FROM Hishop_VoteItems WHERE VoteId = Hishop_Votes.VoteId) AS VoteCounts
	FROM Hishop_Votes, #PageIndexForVotes
	WHERE 
		Hishop_Votes.VoteId = #PageIndexForVotes.VoteId AND
		#PageIndexForVotes.IndexId > @PageLowerBound AND
		#PageIndexForVotes.IndexId < @PageUpperBound 
	ORDER BY #PageIndexForVotes.IndexId
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_Advertisements]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Advertisements]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Advertisements](
	[AdvPositionId] [int] NOT NULL,
	[AdvertisementId] [int] IDENTITY(1,1) NOT NULL,
	[AdvertisementName] [nvarchar](100) NOT NULL,
	[ImageUrl] [nvarchar](100) NOT NULL,
	[AlternateText] [nvarchar](100) NULL,
	[NavigateUrl] [nvarchar](100) NULL,
	[Impressions] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[IsMemberCreated] [bit] NOT NULL,
 CONSTRAINT [PK_Hishop_Advertisements] PRIMARY KEY CLUSTERED 
(
	[AdvertisementId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ca_Coupons_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ca_Coupons_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[sp_ca_Coupons_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@TotalCoupons int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForFavorites
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		CouponId int
	)	

	INSERT INTO #PageIndexForFavorites(CouponId)
	Exec sp_executesql @sqlPopulate

	SET @TotalCoupons = @@rowcount
	
	SELECT c.*, 
		(SELECT COUNT(CouponId) FROM Hishop_CouponItems WHERE CouponId = c.CouponId) AS SentCount, 
        (SELECT COUNT(cc.ClaimCode) FROM Hishop_ClaimedCoupons cc INNER JOIN Hishop_CouponItems ci ON ci.ClaimCode = cc.ClaimCode WHERE ci.CouponId = c.CouponId) AS UsedCount 
    FROM Hishop_Coupons c , #PageIndexForFavorites
	WHERE 
		c.CouponId = #PageIndexForFavorites.CouponId AND
		#PageIndexForFavorites.IndexId > @PageLowerBound AND
		#PageIndexForFavorites.IndexId < @PageUpperBound 
	ORDER BY #PageIndexForFavorites.IndexId
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_PointDetails]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PointDetails]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PointDetails](
	[JournalNumber] [bigint] IDENTITY(1,1) NOT NULL,
	[OrderId] [nvarchar](50) NULL,
	[UserId] [int] NOT NULL,
	[TradeDate] [datetime] NOT NULL,
	[TradeType] [int] NOT NULL,
	[Increased] [int] NULL,
	[Reduced] [int] NULL,
	[Points] [int] NULL,
	[Remark] [nvarchar](200) NULL
)
END
GO
/****** Object:  Table [dbo].[Hishop_OrderLeaveWords]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_OrderLeaveWords]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_OrderLeaveWords](
	[LeaveId] [bigint] IDENTITY(1,1) NOT NULL,
	[OrderId] [nvarchar](50) NOT NULL,
	[PublishContent] [nvarchar](4000) NOT NULL,
	[UserId] [int] NOT NULL,
	[PublishDate] [datetime] NOT NULL,
	[IsAgentVisited] [bit] NOT NULL,
	[IsMemberVisited] [bit] NOT NULL,
	[IsadminVisited] [bit] NOT NULL,
 CONSTRAINT [PK_Hishop_OrderLeaveWords] PRIMARY KEY CLUSTERED 
(
	[LeaveId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_BrandCategorie_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_BrandCategorie_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_BrandCategorie_Get]
(
 	@PageIndex   INT,
	@PageSize	 INT,
	@IsCount	 BIT
)
as
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn	INT
	DECLARE @TotalRecords	INT

	SET @TotalRecords = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexBrandForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		BrandId INT,
	)
	
	INSERT INTO #PageIndexBrandForSearch (BrandId)
	SELECT BrandId FROM Hishop_BrandCategories
	
	SET @TotalRecords = @@ROWCOUNT
	
		SELECT
		b.*
	FROM 
		Hishop_BrandCategories b (nolock),
		#PageIndexBrandForSearch
	WHERE 
		b.BrandId = #PageIndexBrandForSearch.BrandId AND
		#PageIndexBrandForSearch.IndexId > @PageLowerBound AND
		#PageIndexBrandForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexBrandForSearch.IndexId
		
	SELECT @TotalRecords
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_UserPoints_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_UserPoints_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_UserPoints_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@UserId int,
	@sqlPopulate ntext,
	@Total int = 0 output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForPoints
	(
		[IndexId] int IDENTITY (1, 1) NOT NULL,
		[JournalNumber] int,
	)	

	INSERT INTO #PageIndexForPoints (JournalNumber) 
    Exec sp_executesql @sqlPopulate
	SET @Total = @@rowcount
 
	SELECT pd.JournalNumber,pd.OrderId,pd.TradeDate,pd.TradeType,pd.Increased,pd.Reduced,pd.Points
	FROM Hishop_PointDetails pd, #PageIndexForPoints
	WHERE 
		pd.UserId = @UserId AND 
		pd.JournalNumber = #PageIndexForPoints.JournalNumber AND
		#PageIndexForPoints.IndexId > @PageLowerBound AND
		#PageIndexForPoints.IndexId < @PageUpperBound 
	ORDER BY #PageIndexForPoints.IndexId	

END' 
END
GO
/****** Object:  Table [dbo].[Hishop_AdvPositions]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_AdvPositions]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_AdvPositions](
	[AdvPositionId] [int] NOT NULL,
	[AdvPositionName] [nvarchar](100) NOT NULL,
	[ShowType] [int] NOT NULL,
	[RepeatColumns] [int] NULL,
	[Width] [int] NOT NULL,
	[Height] [int] NOT NULL,
	[AdvHtml] [ntext] NULL,
 CONSTRAINT [PK_Hishop_AdvPositions] PRIMARY KEY CLUSTERED 
(
	[AdvPositionId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_DeductRequest]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_DeductRequest]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_DeductRequest](
	[DeductId] [bigint] IDENTITY(1,1) NOT NULL,
	[DeductType] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[KidUserId] [int] NOT NULL,
	[OrderId] [nvarchar](50) NOT NULL,
	[DeductDate] [datetime] NOT NULL,
	[DeductValues] [money] NOT NULL,
 CONSTRAINT [PK_Hishop_DeductRequest] PRIMARY KEY CLUSTERED 
(
	[DeductId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_ProductSKUs_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_ProductSKUs_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_ProductSKUs_Get]
	(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalProducts INT

	SET @TotalProducts = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex - 1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		RealSKU NVARCHAR(50) NOT NULL,
		ProductId INT NOT NULL,
		RealStock INT NULL,
		Price MONEY NULL,
		AttributeNames NVARCHAR(500) NULL,
		AttributeValues NVARCHAR(500) NULL
	)
	
	INSERT INTO #PageIndexForSearch (RealSKU, ProductId, RealStock, Price, AttributeNames, AttributeValues) EXEC sp_executesql @SqlPopulate
	
	SET @TotalProducts = @@ROWCOUNT
	
	SELECT
		s.RealSKU, s.RealStock, ISNULL(s.Price,0) + p.SalePrice AS RealPrice, s.AttributeValues, p.*
	FROM 
		Hishop_Products p (nolock),
		#PageIndexForSearch s
	WHERE 
		p.ProductId = s.ProductId AND
		s.IndexId > @PageLowerBound AND
		s.IndexId < @PageUpperBound
	ORDER BY
		s.IndexId
END

IF (@IsCount = 1)
	SELECT @TotalProducts' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_Attributes_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_Attributes_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_Attributes_Get]
	(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalAttribute INT

	SET @TotalAttribute = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		AttributeId INT,
	)
	
	INSERT INTO #PageIndexForSearch (AttributeId) EXEC sp_executesql @SqlPopulate
	
	SET @TotalAttribute = @@ROWCOUNT	
		
	
	SELECT Hishop_AttributeValues.* FROM Hishop_AttributeValues inner join #PageIndexForSearch	on Hishop_AttributeValues.AttributeId = #PageIndexForSearch.AttributeId 
	WHERE #PageIndexForSearch.IndexId > @PageLowerBound AND #PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY #PageIndexForSearch.IndexId
	
	SELECT Hishop_Attributes.*, (SELECT TypeName FROM Hishop_ProductTypes WHERE TypeId = Hishop_Attributes.TypeId) AS TypeName
	FROM	Hishop_Attributes inner join #PageIndexForSearch	on Hishop_Attributes.AttributeId = #PageIndexForSearch.AttributeId 
	WHERE #PageIndexForSearch.IndexId > @PageLowerBound AND #PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY #PageIndexForSearch.IndexId

IF (@IsCount = 1)
	SELECT @TotalAttribute
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_PaymentCurrencys]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PaymentCurrencys]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PaymentCurrencys](
	[Code] [nvarchar](20) NOT NULL,
	[ModeId] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_PaymentCurrencys] PRIMARY KEY CLUSTERED 
(
	[Code] ASC,
	[ModeId] ASC
)
)
END
GO
/****** Object:  UserDefinedFunction [dbo].[F_SplitToInt]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[F_SplitToInt]') AND xtype in (N'FN', N'IF', N'TF'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE FUNCTION [dbo].[F_SplitToInt]
(
	@str nvarchar(4000), 
	@spliter nvarchar(2)
)
RETURNS @returntable TABLE (UnitInt INT)
AS
BEGIN
	WHILE(CHARINDEX(@spliter,@str)<>0)  
	BEGIN  
		INSERT INTO @returntable(UnitInt) SELECT CAST (SUBSTRING(@str,1,CHARINDEX(@spliter,@str)-1) AS INT)
		SET @str = STUFF(@str,1,CHARINDEX(@spliter,@str),'''')  
	END
	
	INSERT INTO @returntable(UnitInt) SELECT CAST (@str AS INT) 
      
	RETURN 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_UpgradeMemberToAgent]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_UpgradeMemberToAgent]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_UpgradeMemberToAgent]
	(
		@UserId INT,
		@UserRank INT,
		@Expires DATETIME,
		@IsUrlBindApproved bit,
		@Status INT OUTPUT
	)
AS	
    UPDATE Hishop_UserProfile SET UserRank = @UserRank, Agent_Expires = @Expires, Agent_IsUrlBindApproved = @IsUrlBindApproved WHERE UserId = @UserId
    
    IF @@ROWCOUNT = 1
		SET @Status = 0
	ELSE
		SET @Status = 99' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_GetAnonymousUserID]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_GetAnonymousUserID]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Proc [dbo].[sp_GetAnonymousUserID]
(
	@UserId int output
)
as
SET Transaction Isolation Level Read UNCOMMITTED
Select @UserId = hi_UserId FROM vw_Users_FullUser where IsAnonymous = 1' 
END
GO
/****** Object:  UserDefinedFunction [dbo].[F_SplitToString]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[F_SplitToString]') AND xtype in (N'FN', N'IF', N'TF'))
BEGIN
execute dbo.sp_executesql @statement = N'CREATE FUNCTION [dbo].[F_SplitToString]
(
	@str nvarchar(4000), 
	@spliter nvarchar(2)
)
RETURNS @returntable TABLE (UnitString nvarchar(50))
AS
BEGIN
	WHILE(CHARINDEX(@spliter,@str)<>0)  
	BEGIN  
		INSERT INTO @returntable(UnitString) VALUES (SUBSTRING(@str,1,CHARINDEX(@spliter,@str)-1))  
		SET @str = STUFF(@str,1,CHARINDEX(@spliter,@str),'''')  
	END
	
	INSERT INTO @returntable(UnitString) VALUES (@str) 
      
	RETURN 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_ProductSales_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_ProductSales_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'
CREATE PROCEDURE [dbo].[sp_cs_ProductSales_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@TotalProductSales int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForProductSales
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		ProductId int,
		ProductSaleCounts int,
		ProductSaleTotals money,
		ProductProfitsTotals money
	)	

	INSERT INTO #PageIndexForProductSales(ProductId, ProductSaleCounts, ProductSaleTotals, ProductProfitsTotals)
	Exec sp_executesql @sqlPopulate

	SET @TotalProductSales = @@rowcount
	
	SELECT IDOfSaleTotals=(select count(1)+1 from #PageIndexForProductSales where ProductSaleTotals>s.ProductSaleTotals),
		P.ProductName,P.SKU,
		case when S.ProductSaleCounts is null then 0 else S.ProductSaleCounts end as ProductSaleCounts , 
		case when S.ProductSaleTotals is null then 0 else S.ProductSaleTotals end as ProductSaleTotals , 
		case when S.ProductProfitsTotals is null then 0 else S.ProductProfitsTotals end as ProductProfitsTotals
	FROM   Hishop_Products P, #PageIndexForProductSales S
	WHERE 
			P.ProductId = S.ProductId AND
			S.IndexId > @PageLowerBound AND
			S.IndexId < @PageUpperBound 
	ORDER BY S.IndexId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cd_ShoppingCartGifts_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cd_ShoppingCartGifts_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cd_ShoppingCartGifts_Get]
(
	@GiftIdList nvarchar(4000)
)
AS
	CREATE TABLE #idTable (GiftId INT)
	INSERT INTO #idTable(GiftId) SELECT UnitInt FROM F_SplitToInt(@GiftIdList, '','')
	
	SELECT 
		g.GiftId, g.Stock, g.ThumbnailsUrl, g.Name, ISNULL(g.CostPrice, 0.00) AS CostPrice, ISNULL(g.SalePrice, 0.00) AS SalePrice, g.Weight
	FROM
		Hishop_Gifts g INNER JOIN #idTable ON g.GiftId = #idTable.GiftId
		
	DROP TABLE #idTable' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_ProductVisitAndBuyStatistics_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_ProductVisitAndBuyStatistics_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_ProductVisitAndBuyStatistics_Get]
(
	@PageIndex int,
	@PageSize int,
	@sqlPopulate ntext,
	@TotalProductSales int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForProductSales
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		ProductId int,
		BuyCount int,
		BuyPercentage decimal(18, 0)
	)	

	INSERT INTO #PageIndexForProductSales(ProductId, BuyCount,BuyPercentage)
	Exec sp_executesql @sqlPopulate

	SET @TotalProductSales = @@rowcount
	
	SELECT P.*,S.BuyCount ,S.BuyPercentage    
	FROM   Hishop_Products P, #PageIndexForProductSales S
	WHERE 
			P.ProductId = S.ProductId AND
			S.IndexId > @PageLowerBound AND
			S.IndexId < @PageUpperBound 
	ORDER BY S.IndexId
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_PromoteSales_Products]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_PromoteSales_Products]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_PromoteSales_Products](
	[ActivityId] [int] NOT NULL,
	[ProductId] [int] NOT NULL,
	[Type] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_PromoteSales_Products_1] PRIMARY KEY CLUSTERED 
(
	[ActivityId] ASC,
	[ProductId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_ProductSalesNoPage_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_ProductSalesNoPage_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_ProductSalesNoPage_Get]
(
	@sqlPopulate ntext,
	@TotalProductSales int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	CREATE TABLE #PageIndexForProductSales
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		ProductId int,
		ProductSaleCounts int,
		ProductSaleTotals money,
		ProductProfitsTotals money
	)	

	INSERT INTO #PageIndexForProductSales(ProductId, ProductSaleCounts, ProductSaleTotals, ProductProfitsTotals)
	Exec sp_executesql @sqlPopulate

	SET @TotalProductSales = @@rowcount
	
	SELECT IDOfSaleTotals=(select count(1)+1 from #PageIndexForProductSales where ProductSaleTotals>s.ProductSaleTotals),
		P.ProductName,P.SKU,
		case when S.ProductSaleCounts is null then 0 else S.ProductSaleCounts end as ProductSaleCounts , 
		case when S.ProductSaleTotals is null then 0 else S.ProductSaleTotals end as ProductSaleTotals , 
		case when S.ProductProfitsTotals is null then 0 else S.ProductProfitsTotals end as ProductProfitsTotals
	FROM   Hishop_Products P, #PageIndexForProductSales S
	WHERE 
			P.ProductId = S.ProductId
	ORDER BY S.IndexId
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_Gifts]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Gifts]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Gifts](
	[GiftId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[ShortDescription] [nvarchar](2000) NULL,
	[Unit] [nvarchar](50) NULL,
	[Weight] [int] NOT NULL,
	[LongDescription] [ntext] NULL,
	[Title] [nvarchar](100) NULL,
	[Meta_Description] [nvarchar](1000) NULL,
	[Meta_Keywords] [nvarchar](1000) NULL,
	[ThumbnailsUrl] [nvarchar](255) NULL,
	[InFocusImageUrl] [nvarchar](255) NULL,
	[CostPrice] [money] NULL,
	[MarketPrice] [money] NULL,
	[Enabled] [bit] NOT NULL,
	[SalePrice] [money] NULL,
	[Stock] [int] NULL
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_MemberStatisticsNoPage_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_MemberStatisticsNoPage_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_MemberStatisticsNoPage_Get]
(
	@sqlPopulate ntext,
	@TotalProductSales int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	CREATE TABLE #PageIndexForProductSales
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		hi_userId int,
		SaleTotals money default(0),
		OrderCount int default(0)
	)	

	INSERT INTO #PageIndexForProductSales(hi_userId, SaleTotals, OrderCount)
	Exec sp_executesql @sqlPopulate

	SET @TotalProductSales = @@rowcount
	
	SELECT S.IndexId,
		f.username, 
	    case when S.SaleTotals is null then 0 else S.SaleTotals end as SaleTotals ,
        case when S.OrderCount is null then 0 else S.OrderCount end as OrderCount
	FROM   vw_Users_FullUser f, #PageIndexForProductSales S
	WHERE 
			f.hi_userId = S.hi_userId
	ORDER BY S.IndexId
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_ProductReviews]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ProductReviews]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ProductReviews](
	[ReviewId] [bigint] IDENTITY(1,1) NOT NULL,
	[ProductId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[ReviewText] [nvarchar](3000) NOT NULL,
	[UserName] [nvarchar](100) NOT NULL,
	[ReviewDate] [datetime] NOT NULL,
 CONSTRAINT [PK_Hishop_ProductReviews] PRIMARY KEY CLUSTERED 
(
	[ReviewId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_ProductVisitAndBuyStatisticsNoPage_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_ProductVisitAndBuyStatisticsNoPage_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_ProductVisitAndBuyStatisticsNoPage_Get]
(
	@sqlPopulate ntext,
	@TotalProductSales int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	CREATE TABLE #PageIndexForProductSales
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		ProductId int,
		BuyCount int,
		BuyPercentage decimal(18, 0)
	)	

	INSERT INTO #PageIndexForProductSales(ProductId, BuyCount,BuyPercentage)
	Exec sp_executesql @sqlPopulate

	SET @TotalProductSales = @@rowcount
	
	SELECT P.*,S.BuyCount ,S.BuyPercentage    
	FROM   Hishop_Products P, #PageIndexForProductSales S
	WHERE 
			P.ProductId = S.ProductId
	ORDER BY S.IndexId
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_RelatedProducts]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_RelatedProducts]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_RelatedProducts](
	[ProductId] [int] NOT NULL,
	[RelatedProductId] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_RelatedProducts] PRIMARY KEY CLUSTERED 
(
	[ProductId] ASC,
	[RelatedProductId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_UserOrdersNoPage_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_UserOrdersNoPage_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_UserOrdersNoPage_Get]
(
	@sqlPopulate ntext,
	@TotalUserOrders int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN

	CREATE TABLE #PageIndexForUserOrders
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		OrderId nvarchar(50)
	)	

	INSERT INTO #PageIndexForUserOrders(OrderId)
	Exec sp_executesql @sqlPopulate

	SET @TotalUserOrders = @@rowcount
	
	SELECT O.OrderId, OrderDate, Isnull(OrderTotal,0) as Total, Username, ShipTo, Isnull(OrderProfit,0) As Profits,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId =
		(SELECT ReferralUserId FROM vw_Users_FullUser WHERE hi_UserId = O.UserId)) AS Referral,
		(SELECT DeductValues FROM Hishop_DeductRequest WHERE OrderId = O.OrderId AND KidUserId = O.UserId AND DeductType = 2) AS RdferralDeduct,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId =
		(SELECT ParentUserId FROM vw_Users_FullUser WHERE hi_UserId = O.UserId)) AS Parent,
		(SELECT DeductValues FROM Hishop_DeductRequest WHERE OrderId = O.OrderId AND KidUserId = O.UserId AND DeductType = 1) AS ParentDeduct
	FROM Hishop_Orders O, #PageIndexForUserOrders UO 
	WHERE 
			O.OrderId = UO.OrderId
	ORDER BY UO.IndexId 
    ------------------------------------------------------------
    -- 当次搜索结果,总金额,利润
    SELECT 
		Isnull(SUM(OrderTotal),0) AS OrderTotal, -- 总金额
        Isnull(SUM(OrderProfit),0) AS Profits --利润
	FROM Hishop_Orders o,#PageIndexForUserOrders
    where
       o.OrderId = #PageIndexForUserOrders.OrderId
    -- 当次搜索结果,代理商利润
    select SUM(d.DeductValues) AS Deduct 
	from Hishop_DeductRequest d,#PageIndexForUserOrders
    where
	   deductType=1 and
       d.OrderId = #PageIndexForUserOrders.OrderId 
    -- 当次搜索结果,推荐人利润
    select SUM(d.DeductValues) AS Deduct 
	from Hishop_DeductRequest d,#PageIndexForUserOrders
    where
	   deductType=2 and
       d.OrderId = #PageIndexForUserOrders.OrderId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_UserOrders_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_UserOrders_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_UserOrders_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@TotalUserOrders int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForUserOrders
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		OrderId nvarchar(50)
	)	

	INSERT INTO #PageIndexForUserOrders(OrderId)
	Exec sp_executesql @sqlPopulate

	SET @TotalUserOrders = @@rowcount
	
	SELECT O.OrderId, OrderDate, Isnull(OrderTotal,0) as Total, Username, ShipTo,Isnull(OrderProfit,0) As Profits,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId =
		(SELECT ReferralUserId FROM vw_Users_FullUser WHERE hi_UserId = O.UserId)) AS Referral,
		(SELECT DeductValues FROM Hishop_DeductRequest WHERE OrderId = O.OrderId AND KidUserId = O.UserId AND DeductType = 2) AS RdferralDeduct,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId =
		(SELECT ParentUserId FROM vw_Users_FullUser WHERE hi_UserId = O.UserId)) AS Parent,
		(SELECT DeductValues FROM Hishop_DeductRequest WHERE OrderId = O.OrderId AND KidUserId = O.UserId AND DeductType = 1) AS ParentDeduct
	FROM Hishop_Orders O, #PageIndexForUserOrders UO 
	WHERE 
			O.OrderId = UO.OrderId AND
			UO.IndexId > @PageLowerBound AND
			UO.IndexId < @PageUpperBound
	ORDER BY UO.IndexId 
    ------------------------------------------------------------
    -- 当页搜索结果,总金额,利润
    SELECT 
		Isnull(SUM(OrderTotal),0) AS OrderTotal, -- 总金额
        Isnull(SUM(OrderProfit),0) AS Profits --利润
	FROM Hishop_Orders o,#PageIndexForUserOrders
    where
       o.OrderId = #PageIndexForUserOrders.OrderId and
       #PageIndexForUserOrders.IndexId > @PageLowerBound and  
	   #PageIndexForUserOrders.IndexId < @PageUpperBound
    -- 当页搜索结果,代理商利润
    select SUM(d.DeductValues) AS Deduct 
	from Hishop_DeductRequest d,#PageIndexForUserOrders
    where
	   deductType=1 and
       d.OrderId = #PageIndexForUserOrders.OrderId and
       #PageIndexForUserOrders.IndexId > @PageLowerBound and  
	   #PageIndexForUserOrders.IndexId < @PageUpperBound   
    -- 当页搜索结果,推荐人利润
    select SUM(d.DeductValues) AS Deduct 
	from Hishop_DeductRequest d,#PageIndexForUserOrders
    where
	   deductType=2 and
       d.OrderId = #PageIndexForUserOrders.OrderId and
       #PageIndexForUserOrders.IndexId > @PageLowerBound and  
	   #PageIndexForUserOrders.IndexId < @PageUpperBound  
    -------------------------------------------------------------
    -- 当次搜索结果,总金额,利润
    SELECT 
		Isnull(SUM(OrderTotal),0) AS OrderTotal, -- 总金额
        Isnull(SUM(OrderProfit),0) AS Profits --利润
	FROM Hishop_Orders o,#PageIndexForUserOrders
    where
       o.OrderId = #PageIndexForUserOrders.OrderId
    -- 当次搜索结果,代理商利润
    select SUM(d.DeductValues) AS Deduct 
	from Hishop_DeductRequest d,#PageIndexForUserOrders
    where
	   deductType=1 and
       d.OrderId = #PageIndexForUserOrders.OrderId 
    -- 当次搜索结果,推荐人利润
    select SUM(d.DeductValues) AS Deduct 
	from Hishop_DeductRequest d,#PageIndexForUserOrders
    where
	   deductType=2 and
       d.OrderId = #PageIndexForUserOrders.OrderId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_SubRegions_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_SubRegions_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_SubRegions_Get]
	@PageIndex   INT,
	@PageSize	 INT,
	@IsCount	 BIT,
	@ParentId	 INT
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn	INT
	DECLARE @TotalRecords	INT
    DECLARE @Sql			NVARCHAR(4000)
	
	SET @Sql=''SELECT RegionId FROM Hishop_Regions WHERE ParentId =''+str(@ParentId)
	SET @TotalRecords = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	SET @Sql=@Sql+'' ORDER BY DisplaySequence''

	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		RegionId INT,
	)
	
	INSERT INTO #PageIndexForSearch (RegionId)
	Exec(@Sql)
	
	SET @TotalRecords = @@ROWCOUNT
	
		SELECT
		r.*
	FROM 
		Hishop_Regions r (nolock),
		#PageIndexForSearch
	WHERE 
		r.RegionId = #PageIndexForSearch.RegionId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId
		
	SELECT @TotalRecords
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cd_ProductSkus_GetBySkus]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cd_ProductSkus_GetBySkus]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cd_ProductSkus_GetBySkus]
(
	@Skus nvarchar(4000)
)
AS
	CREATE TABLE #skuTable (IndexId INT IDENTITY(1,1), SKU nvarchar(50))
	INSERT INTO #skuTable(SKU) SELECT UnitString FROM F_SplitToString(@Skus, '','')
	
	SELECT 
		s.SKU, s.AttributeNames, s.AttributeValues, s.ProductId, s.Stock, ISNULL(s.Price, 0) AS SKUPrice, 
		p.UpSelling, p.MinQuantity, p.QuantityLimit, p.ThumbnailsUrl, p.ProductName 
	FROM
		Hishop_SKUs s INNER JOIN #skuTable ON s.SKU = #skuTable.SKU
		INNER JOIN Hishop_Products p ON s.ProductId = p.ProductId		

	DROP TABLE #skuTable' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_RegionsUsers_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_RegionsUsers_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_RegionsUsers_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@TotalRegionsUsers int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForRegionsUsers
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		RegionId int,
		RegionName char(100),
		UserCounts int,
		AllUserCounts int
	)	

	INSERT INTO #PageIndexForRegionsUsers(RegionId, RegionName, UserCounts, AllUserCounts)
	Exec sp_executesql @sqlPopulate

	SET @TotalRegionsUsers = @@rowcount
	
	SELECT RU.RegionId, RU.RegionName, RU.UserCounts, RU.AllUserCounts
	FROM   #PageIndexForRegionsUsers RU
	WHERE 
			RU.IndexId > @PageLowerBound AND
			RU.IndexId < @PageUpperBound
	ORDER BY RU.IndexId
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_Users]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Users]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Users](
	[MembershipId] [uniqueidentifier] NOT NULL,
	[UserId] [int] IDENTITY(1100,1) NOT NULL,
	[ForceLogin] [bit] NOT NULL,
	[UserAccountStatus] [smallint] NOT NULL,
	[AppUserToken] [nvarchar](128) NULL,
	[LastActivity] [datetime] NOT NULL,
	[LastAction] [nvarchar](1024) NULL,
	[Deleted] [bit] NOT NULL,
 CONSTRAINT [PK_Hishop_Users] PRIMARY KEY CLUSTERED 
(
	[UserId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_MemberStatistics_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_MemberStatistics_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_MemberStatistics_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@TotalProductSales int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForProductSales
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		hi_userId int,
		SaleTotals money default(0),
		OrderCount int default(0)
	)	

	INSERT INTO #PageIndexForProductSales(hi_userId, SaleTotals, OrderCount)
	Exec sp_executesql @sqlPopulate

	SET @TotalProductSales = @@rowcount
	
	SELECT S.IndexId,
		f.username, 
	    case when S.SaleTotals is null then 0 else S.SaleTotals end as SaleTotals ,
        case when S.OrderCount is null then 0 else S.OrderCount end as OrderCount
	FROM   vw_Users_FullUser f, #PageIndexForProductSales S
	WHERE 
			f.hi_userId = S.hi_userId AND
			S.IndexId > @PageLowerBound AND
			S.IndexId < @PageUpperBound 
	ORDER BY S.IndexId
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_IntegrationSettings]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_IntegrationSettings]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_IntegrationSettings](
	[IntegrationForumId] [int] IDENTITY(1,1) NOT NULL,
	[applicationName] [nvarchar](200) NOT NULL,
	[IntegrationForumXML] [ntext] NOT NULL,
	[IsOff] [bit] NOT NULL,
	[IsUsing] [bit] NOT NULL,
	[IntegrationForumURL] [nvarchar](200) NOT NULL
)
END
GO
/****** Object:  Table [dbo].[Hishop_Attributes]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Attributes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Attributes](
	[AttributeId] [int] IDENTITY(1,1) NOT NULL,
	[AttributeName] [nvarchar](50) NOT NULL,
	[DisplaySequence] [int] NOT NULL,
	[TypeId] [int] NOT NULL,
	[UsageMode] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_Attributes] PRIMARY KEY CLUSTERED 
(
	[AttributeId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_Logs]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Logs]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Logs](
	[LogId] [bigint] IDENTITY(1,1) NOT NULL,
	[ResourceName] [nvarchar](200) NOT NULL,
	[OperationName] [nvarchar](200) NOT NULL,
	[PageUrl] [nvarchar](255) NOT NULL,
	[AddedTime] [datetime] NOT NULL,
	[UserName] [nvarchar](64) NOT NULL,
	[IPAddress] [nvarchar](50) NOT NULL,
	[Description] [ntext] NULL,
 CONSTRAINT [PK_Hishop_Logs] PRIMARY KEY CLUSTERED 
(
	[LogId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[spb_PriceChangeLogs_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[spb_PriceChangeLogs_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spb_PriceChangeLogs_Get]
(
 	@PageIndex		 INT,
	@PageSize		 INT,
	@IsCount	     BIT,
    @SqlPopulate     NTEXT  
)
as
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @TotalRecords	INT
   
	SET @TotalRecords = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		RecordId BIGINT,
	)
	
	INSERT INTO #PageIndexForSearch (RecordId)
	Exec sp_executesql @SqlPopulate
	
    SET @TotalRecords = @@rowcount
	
	 SELECT
		c.*,
		(select UserName from vw_Users_FullUser where Hi_UserId=c.UserId) as UserName,
        (select Name from Hishop_Categories where CategoryId=c.CategoryId) as CategoryName
	FROM 
		Hishop_PriceChangeLogs c (nolock),
		#PageIndexForSearch
	WHERE 
		c.RecordId = #PageIndexForSearch.RecordId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
        
	ORDER BY
		#PageIndexForSearch.IndexId
END

   SELECT @TotalRecords' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_EmailToUser_Enqueue]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_EmailToUser_Enqueue]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[sp_cg_EmailToUser_Enqueue]
(
	@SqlPopulate NTEXT,
	@EmailCc	ntext,
	@EmailBcc	ntext,
	@EmailFrom	nvarchar(256),
	@EmailSubject	nvarchar(1024),
	@EmailBody	ntext,
	@EmailPriority	int,
	@IsBodyHtml bit,
	@TotalSend  int = 0 output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	CREATE TABLE #UserEmailis 
	(
		Email nvarchar(2000)
	)
	INSERT INTO #UserEmailis (Email) EXEC sp_executesql @SqlPopulate

	INSERT INTO Hishop_EmailQueue(emailTo,emailCc,emailBcc,EmailFrom,EmailSubject,EmailBody,emailPriority,IsBodyHtml)
	SELECT Email,@EmailCc,@EmailBcc,@EmailFrom,@EmailSubject,@EmailBody,@EmailPriority,@IsBodyHtml 
	FROM #UserEmailis
 	SET @TotalSend = @@rowcount
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_ClaimedCoupons]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ClaimedCoupons]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ClaimedCoupons](
	[UserId] [int] NOT NULL,
	[ClaimCode] [nvarchar](50) NOT NULL,
	[DateClaimed] [datetime] NOT NULL
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_Users_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_Users_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_Users_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsIncludeStatistic bit,
	@sqlPopulate ntext,
	@Total int = 0 output
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

-- Set the page bounds
SET @PageLowerBound = @PageSize * (@PageIndex-1)
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

CREATE TABLE #PageIndexForUsers 
(
	IndexId int IDENTITY (1, 1) NOT NULL,
	hi_UserId int,
	SubordinateUserNumb int,
	ReferralUserNumb int,
	ParentUserName nvarchar(256)
)	

INSERT INTO #PageIndexForUsers (hi_UserId,SubordinateUserNumb,ReferralUserNumb,ParentUserName)
Exec sp_executesql @sqlPopulate

SET @Total = @@rowcount

-- 分页搜索结果
SELECT
	U.*,
	ISNULL(Balance,0) as UserBalance,
	ISNULL(DeductMoney,0) as UserDeductMoney,
	ISNULL(OrderNumber,0) as UserOrderNumber,
	ISNULL(#PageIndexForUsers.ParentUserName,'''') as ParentUserName,
	#PageIndexForUsers.SubordinateUserNumb as SubordinateUserNumb,
	#PageIndexForUsers.ReferralUserNumb as  ReferralUserNumb
FROM 
	vw_Users_FullUser U (nolock),
	#PageIndexForUsers
WHERE 
	U.hi_UserId = #PageIndexForUsers.hi_UserId AND
	#PageIndexForUsers.IndexId > @PageLowerBound AND
	#PageIndexForUsers.IndexId < @PageUpperBound
ORDER BY
	#PageIndexForUsers.IndexId


if (@IsIncludeStatistic=1)
begin

	-- 当页搜索结果,预付款,提成,订单
	select 
	    isnull(Sum(OrderNumber),0) as OrderNumber,
		isnull(Sum(Balance),0) as Balance,
		isnull(Sum(DeductMoney),0) as DeductMoney
	from vw_Users_FullUser b  ,#PageIndexForUsers
	where 
		b.hi_UserId = #PageIndexForUsers.hi_UserId AND
		#PageIndexForUsers.IndexId > @PageLowerBound AND
		#PageIndexForUsers.IndexId < @PageUpperBound
		
	-- 当页搜索结果,下级会员数量,推荐会员数量
	select 
	    ( select Count(Hi_UserId) from vw_Users_FullUser where ParentUserId is not null ) as SubordinateUserNumb,
		( select Count(Hi_UserId) from vw_Users_FullUser where ReferralUserId is not null ) as ReferralUserNumb
	from vw_Users_FullUser b  ,#PageIndexForUsers
	where 
		b.hi_UserId = #PageIndexForUsers.hi_UserId AND
		#PageIndexForUsers.IndexId > @PageLowerBound AND
		#PageIndexForUsers.IndexId < @PageUpperBound
		
	-- 当次搜索结果,预付款,提成,订单
	select 
	    isnull(Sum(OrderNumber),0) as OrderNumber,
		isnull(Sum(Balance),0) as Balance,
		isnull(Sum(DeductMoney),0) as DeductMoney
	from vw_Users_FullUser b  ,#PageIndexForUsers
	where 
		b.hi_UserId = #PageIndexForUsers.hi_UserId 
    
	-- 当次搜索结果,下级会员数量,推荐会员数量
	select 
	    ( select Count(Hi_UserId) from vw_Users_FullUser where ParentUserId is not null ) as SubordinateUserNumb,
		( select Count(Hi_UserId) from vw_Users_FullUser where ReferralUserId is not null ) as ReferralUserNumb
	from vw_Users_FullUser b  ,#PageIndexForUsers
	where 
		b.hi_UserId = #PageIndexForUsers.hi_UserId
		
	-- 当次搜索结果
	SELECT
		U.HI_userId,
		ISNULL(Balance,0) as UserBalance,
		ISNULL(DeductMoney,0) as UserDeductMoney,
		ISNULL(OrderNumber,0) as UserOrderNumber,
		ISNULL(#PageIndexForUsers.ParentUserName,'''') as ParentUserName,
		#PageIndexForUsers.SubordinateUserNumb as SubordinateUserNumb,
		#PageIndexForUsers.ReferralUserNumb as  ReferralUserNumb
	FROM 
		vw_Users_FullUser U (nolock),
		#PageIndexForUsers
	WHERE 
		U.hi_UserId = #PageIndexForUsers.hi_UserId
	ORDER BY
		#PageIndexForUsers.IndexId
end

END

	SELECT @Total' 
END
GO
/****** Object:  Table [dbo].[Hishop_AgentThemes]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_AgentThemes]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_AgentThemes](
	[AgentId] [int] NOT NULL,
	[ThemeName] [nvarchar](256) NOT NULL,
 CONSTRAINT [PK_Hishop_AgentThemes] PRIMARY KEY CLUSTERED 
(
	[AgentId] ASC,
	[ThemeName] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_User_GetByEmail]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_User_GetByEmail]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[sp_User_GetByEmail]
(
	@Email		nvarchar(64)
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT 
	hi_UserId
FROM
	vw_Users_FullUser
WHERE
	Email = @Email' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_UserReviewsAndReplys_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_UserReviewsAndReplys_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_UserReviewsAndReplys_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@UserId int,
	@sqlPopulate ntext,
	@Total int = 0 output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForReviewProducts
	(
		[IndexId] int IDENTITY (1, 1) NOT NULL,
		[ProductId] int,
	)	

	INSERT INTO #PageIndexForReviewProducts (ProductId) 
    Exec sp_executesql @sqlPopulate
 
	SELECT pt.ProductId,
		(SELECT ProductName   FROM Hishop_Products WHERE ProductId = pt.ProductId) AS ProductName,
		(SELECT TOP 1 ReviewDate FROM Hishop_ProductReviews 
			WHERE ProductId = pt.ProductId 
			ORDER BY ReviewDate DESC ) AS ReviewLastDate
	FROM Hishop_ProductReviews pt, #PageIndexForReviewProducts
	WHERE 
		pt.UserId = @UserId AND 
		pt.ProductId = #PageIndexForReviewProducts.ProductId AND
		#PageIndexForReviewProducts.IndexId > @PageLowerBound AND
		#PageIndexForReviewProducts.IndexId < @PageUpperBound 
	GROUP BY pt.ProductId
	ORDER BY ReviewLastDate desc	
	SET @Total = @@rowcount

	SELECT r.*,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = r.UserId) AS UserName
    FROM Hishop_ProductReviews r
	WHERE UserId = @UserId
	ORDER BY  ReviewDate DESC

END' 
END
GO
/****** Object:  Table [dbo].[Hishop_OnlineServiceItem]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_OnlineServiceItem]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_OnlineServiceItem](
	[ServiceId] [bigint] IDENTITY(1,1) NOT NULL,
	[ServiceAccount] [nvarchar](200) NOT NULL,
	[ServiceType] [int] NOT NULL,
	[DisplaySequence] [int] NOT NULL,
	[IsShowItem] [bit] NOT NULL,
	[ServiceName] [nvarchar](100) NOT NULL,
	[UserId] [int] NOT NULL,
	[IsMemberCreated] [bit] NOT NULL,
 CONSTRAINT [PK_Hishop_OnlineServiceItem] PRIMARY KEY CLUSTERED 
(
	[ServiceId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_ReviewsAndReplys_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_ReviewsAndReplys_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_ReviewsAndReplys_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@Total int = 0 output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForReviews
	(
		[IndexId] int IDENTITY (1, 1) NOT NULL,
		[ReviewId] int
	)	

	INSERT INTO #PageIndexForReviews (ReviewId) 
    Exec sp_executesql @sqlPopulate

	SET @Total = @@rowcount
		-- 评论记录
		SELECT pr.*,
			(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = pr.UserId) AS UserName, --用户名
			(SELECT Name FROM Hishop_UserRanks 
			 WHERE RankId = (SELECT UserRank FROM Hishop_UserProfile 
							 WHERE UserId = pr.UserId ) ) AS RankName	-- 用户等级	
		FROM Hishop_ProductReviews pr, #PageIndexForReviews
		WHERE  
			pr.ReviewId = #PageIndexForReviews.ReviewId AND
			#PageIndexForReviews.IndexId > @PageLowerBound AND
			#PageIndexForReviews.IndexId < @PageUpperBound 
		ORDER BY #PageIndexForReviews.IndexId desc

END
       SELECT @Total' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_BalanceFreezeDetails_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_BalanceFreezeDetails_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_BalanceFreezeDetails_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@SqlPopulate ntext
)

AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN 
	DECLARE @PageLowerBound int	
	DECLARE @PageUpperBound int
	DECLARE @RowsToReturn int
	DECLARE @TotalBalanceFreezeDetails int
	
	SET @TotalBalanceFreezeDetails = 0 
	--Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForBalanceFreezeDetails
	(
		IndexId int IDENTITY(1,1) NOT NULL,
		JournalNumber bigint
	)

	INSERT INTO #PageIndexForBalanceFreezeDetails(JournalNumber)
	EXEC sp_executesql @SqlPopulate

	SET @TotalBalanceFreezeDetails = @@rowcount
	
	SELECT 
		B.*,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = B.UserId) AS UserName		
	FROM
		Hishop_BalanceFreezeDetails B (nolock),	
		#PageIndexForBalanceFreezeDetails
	WHERE
		B.JournalNumber = #PageIndexForBalanceFreezeDetails.JournalNumber AND
		#PageIndexForBalanceFreezeDetails.IndexId > @PageLowerBound AND
		#PageIndexForBalanceFreezeDetails.IndexId < @PageUpperBound
	ORDER BY 
		#PageIndexForBalanceFreezeDetails.IndexId	
END

--Return the record count
IF (@IsCount = 1)
	SELECT @TotalBalanceFreezeDetails' 
END
GO
/****** Object:  Table [dbo].[aspnet_Applications]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Applications]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[aspnet_Applications](
	[ApplicationName] [nvarchar](256) NOT NULL,
	[LoweredApplicationName] [nvarchar](256) NOT NULL,
	[ApplicationId] [uniqueidentifier] NOT NULL,
	[Description] [nvarchar](256) NULL,
 CONSTRAINT [PK__aspnet_Applicati__78B3EFCA] PRIMARY KEY NONCLUSTERED 
(
	[ApplicationId] ASC
),
 CONSTRAINT [UQ__aspnet_Applicati__79A81403] UNIQUE NONCLUSTERED 
(
	[LoweredApplicationName] ASC
),
 CONSTRAINT [UQ__aspnet_Applicati__7A9C383C] UNIQUE NONCLUSTERED 
(
	[ApplicationName] ASC
)
)
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[aspnet_Applications]') AND name = N'aspnet_Applications_Index')
CREATE CLUSTERED INDEX [aspnet_Applications_Index] ON [dbo].[aspnet_Applications] 
(
	[LoweredApplicationName] ASC
)
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_Help_Search]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_Help_Search]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_Help_Search]
	@PageIndex INT,
	@PageSize INT,
	@IsCount BIT,
	@Keywords NVARCHAR(100)= null,
    @CategoryId INT		   = null,
	@StartTime NVARCHAR(100)  = null,
	@EndTime NVARCHAR(100)    = null,
	@SortBy		 NVARCHAR(100),
	@SortOrder   NVARCHAR(100),
	@IsMemberCreated BIT = 0,
	@UserId INT = 0
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn	INT
	DECLARE @TotalRecords	INT
    DECLARE @Sql			NVARCHAR(4000)
	
	SET @Sql=''SELECT HelpId FROM Hishop_Helps WHERE 1 = 1 AND IsMemberCreated ='' + str(@IsMemberCreated)
	SET @TotalRecords = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	IF @KeyWords is not null
		SET @Sql=@Sql+'' AND (LOWER(Title) like ''''%''+@Keywords+''%'''' OR LOWER(Description) like ''''%''+@Keywords+''%'''')''
    IF @CategoryId > 0
		SET @Sql=@Sql+'' AND CategoryId = ''+str(@CategoryId)
    IF @StartTime is not null
		SET @Sql=@Sql+'' AND AddedDate >=''''''+@StartTime+''''''''
	IF @EndTime is not null
		SET @Sql=@Sql+'' AND AddedDate <=''''''+@EndTime+''''''''
	IF @IsMemberCreated = 1
		SET @Sql=@Sql+'' AND UserId = '' + str(@UserId)		

	SET @Sql=@Sql+'' ORDER BY ''+@SortBy+ '' ''+ @SortOrder
	
		
	print @Sql
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		HelpId INT,
	)
	
	INSERT INTO #PageIndexForSearch (HelpId)
	Exec(@Sql)
	
	SET @TotalRecords = @@ROWCOUNT
	
		SELECT
		pm.*,pc.[Name]
	FROM 
		Hishop_Helps pm (nolock),
		#PageIndexForSearch,
        Hishop_HelpCategories PC
	WHERE 
		pm.HelpId = #PageIndexForSearch.HelpId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound AND
		pm.CategoryId=pc.CategoryId
	ORDER BY
		#PageIndexForSearch.IndexId
		
	SELECT @TotalRecords
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_Affiche]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Affiche]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Affiche](
	[AfficheId] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](200) NULL,
	[Content] [ntext] NOT NULL,
	[AddedDate] [datetime] NOT NULL,
	[UserId] [int] NOT NULL,
	[IsMemberCreated] [bit] NOT NULL
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Users_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Users_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Users_Get]
(
	@PageIndex int,
	@PageSize int,
	@sqlPopulate ntext,
	@SearchText nvarchar(256)
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

-- Set the page bounds
SET @PageLowerBound = @PageSize * (@PageIndex-1)
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

CREATE TABLE #PageIndexForUsers 
(
	IndexId int IDENTITY (1, 1) NOT NULL,
	UserId int
)	

DECLARE @ParmDefinition NVARCHAR(500)
SET @ParmDefinition = N''@SearchText nvarchar(256)''

INSERT INTO #PageIndexForUsers (UserId)
Exec sp_executesql @sqlPopulate, @ParmDefinition, @SearchText

SET @TotalUsers = @@rowcount

SELECT
	U.*
FROM 
	vw_Users_FullUser U (nolock),
	#PageIndexForUsers
WHERE 
	U.hi_UserId = #PageIndexForUsers.UserId AND
	#PageIndexForUsers.IndexId > @PageLowerBound AND
	#PageIndexForUsers.IndexId < @PageUpperBound
ORDER BY
	#PageIndexForUsers.IndexId

END

-- Return the record count
SELECT @TotalUsers' 
END
GO
/****** Object:  Table [dbo].[Hishop_Helps]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Helps]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Helps](
	[CategoryId] [int] NOT NULL,
	[HelpId] [int] IDENTITY(1,1) NOT NULL,
	[Title] [nvarchar](200) NOT NULL,
	[Description] [nvarchar](1000) NULL,
	[Content] [ntext] NOT NULL,
	[AddedDate] [datetime] NOT NULL,
	[IsShowFooter] [bit] NOT NULL,
	[UserId] [int] NOT NULL,
	[IsMemberCreated] [bit] NOT NULL
)
END
GO
/****** Object:  Table [dbo].[Hishop_FriendlyLinks]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_FriendlyLinks]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_FriendlyLinks](
	[LinkId] [int] IDENTITY(1,1) NOT NULL,
	[ImageUrl] [nvarchar](255) NULL,
	[LinkUrl] [nvarchar](255) NULL,
	[Title] [nvarchar](100) NULL,
	[Visible] [bit] NOT NULL,
	[DisplaySequence] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[IsMemberCreated] [bit] NOT NULL,
 CONSTRAINT [PK_HiShop_Links] PRIMARY KEY CLUSTERED 
(
	[LinkId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_BalanceDetails_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_BalanceDetails_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_BalanceDetails_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@SqlPopulate ntext
)

AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN 
	DECLARE @PageLowerBound int	
	DECLARE @PageUpperBound int
	DECLARE @RowsToReturn int
	DECLARE @TotalBalanceDetails int
	
	SET @TotalBalanceDetails = 0 
	--Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForBalanceDetails
	(
		IndexId int IDENTITY(1,1) NOT NULL,                                                          
		JournalNumber bigint
	)

	INSERT INTO #PageIndexForBalanceDetails(JournalNumber)
	EXEC sp_executesql @SqlPopulate

	SET @TotalBalanceDetails = @@rowcount
	
	SELECT 
		B.JournalNumber,B.UserId,B.TradeDate,B.TradeType,B.Income,B.Expenses,B.Balance,B.Remark,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = B.Payer) AS PayerName,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = B.Payee) AS PayeeName,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = B.UserId) AS UserName
	FROM
		Hishop_BalanceDetails B ,
		#PageIndexForBalanceDetails			
	WHERE
		B.JournalNumber = #PageIndexForBalanceDetails.JournalNumber AND
		#PageIndexForBalanceDetails.IndexId > @PageLowerBound AND
		#PageIndexForBalanceDetails.IndexId < @PageUpperBound
	ORDER BY 
		#PageIndexForBalanceDetails.IndexId	
END

--Return the record count
IF (@IsCount = 1)
	SELECT @TotalBalanceDetails' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_DeductRequest_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_DeductRequest_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_DeductRequest_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@SqlPopulate ntext
)
AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN 
	DECLARE @PageLowerBound int	
	DECLARE @PageUpperBound int
	DECLARE @RowsToReturn int
	DECLARE @TotalDeductRequest int
	
	SET @TotalDeductRequest = 0 
	--Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForDeductRequest
	(
		IndexId int IDENTITY(1,1) NOT NULL,                                                          
		DeductId bigint
	)

	INSERT INTO #PageIndexForDeductRequest(DeductId)
	EXEC sp_executesql @SqlPopulate

	SET @TotalDeductRequest = @@rowcount
	
	SELECT D.*, (SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = D.KidUserId) AS UserName
	FROM
		Hishop_DeductRequest D,
		#PageIndexForDeductRequest			
	WHERE
		D.DeductId = #PageIndexForDeductRequest.DeductId AND
		#PageIndexForDeductRequest.IndexId > @PageLowerBound AND
		#PageIndexForDeductRequest.IndexId < @PageUpperBound		
	ORDER BY 
		#PageIndexForDeductRequest.IndexId	
END

--Return the record count
IF (@IsCount = 1)
	SELECT @TotalDeductRequest
	
RETURN 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ManageLogsQuery_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ManageLogsQuery_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ManageLogsQuery_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@SqlPopulate ntext
)
AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN 
	DECLARE @PageLowerBound int	
	DECLARE @PageUpperBound int
	DECLARE @RowsToReturn int
	DECLARE @TotalLogs int
	
	SET @TotalLogs = 0 
	--Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForLogs
	(
		IndexId int IDENTITY(1,1) NOT NULL,
		LogId  int
	)

	INSERT INTO #PageIndexForLogs(LogId)
	EXEC sp_executesql @SqlPopulate

	SET @TotalLogs = @@rowcount

	SELECT 
		L.*
	FROM
		Hishop_Logs L (nolock),
		#PageIndexForLogs
	WHERE
		L.LogId = #PageIndexForLogs.LogId AND
		#PageIndexForLogs.IndexId > @PageLowerBound AND
		#PageIndexForLogs.IndexId < @PageUpperBound
	ORDER BY 
		#PageIndexForLogs.IndexId	
END

--Return the record count
IF (@IsCount = 1)
	SELECT @TotalLogs' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Users_UsersInRole_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Users_UsersInRole_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Users_UsersInRole_Get]
(
	@PageIndex int,
	@PageSize int,
	@sqlPopulate ntext
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

-- Set the page bounds
SET @PageLowerBound = @PageSize * (@PageIndex-1)
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

CREATE TABLE #PageIndexForUsers 
(
	IndexId int IDENTITY (1, 1) NOT NULL,
	UserId int
)	

INSERT INTO #PageIndexForUsers (UserId)
Exec sp_executesql @sqlPopulate

SET @TotalUsers = @@rowcount

-- Get the user details
SELECT
	U.*
FROM 
	vw_Users_FullUser U (nolock),
	#PageIndexForUsers
WHERE 
	U.hi_UserId = #PageIndexForUsers.UserId AND
	#PageIndexForUsers.IndexId > @PageLowerBound AND
	#PageIndexForUsers.IndexId < @PageUpperBound
ORDER BY
	#PageIndexForUsers.IndexId
END

SELECT @TotalUsers' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_ProductPricesForAgent_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_ProductPricesForAgent_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_ProductPricesForAgent_Get]
	(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@RankId INT,
		@AgentRankId INT,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalProducts INT

	SET @TotalProducts = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ProductId INT
	)
	

	INSERT INTO #PageIndexForSearch (ProductId) EXEC sp_executesql @SqlPopulate
	
	SET @TotalProducts = @@ROWCOUNT	
		
	BEGIN
		SELECT
			p.*,
			(SELECT ISNULL(SalePrice, p.SalePrice) FROM Hishop_ProductPrices WHERE ProductId=p.ProductId AND RankId=@AgentRankId) AS AgnetRankPrice,
			(SELECT ISNULL(SalePrice, p.SalePrice) FROM Hishop_ProductPrices WHERE ProductId=p.ProductId AND RankId=@RankId) AS RankPrice,
			((SELECT ISNULL(SalePrice, p.SalePrice) FROM Hishop_ProductPrices WHERE ProductId=p.ProductId AND RankId=@RankId) - (SELECT ISNULL(SalePrice, p.SalePrice) FROM Hishop_ProductPrices WHERE ProductId=p.ProductId AND RankId=@AgentRankId)) AS Profit 
		FROM 			
			Hishop_Products p(nolock) inner join #PageIndexForSearch	on p.ProductId = #PageIndexForSearch.ProductId 
		WHERE
			#PageIndexForSearch.IndexId > @PageLowerBound AND
			#PageIndexForSearch.IndexId < @PageUpperBound
		ORDER BY
			#PageIndexForSearch.IndexId
	END

IF (@IsCount = 1)
	SELECT @TotalProducts
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_Hotkeywords]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_Hotkeywords]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_Hotkeywords](
	[Hid] [int] IDENTITY(1,1) NOT NULL,
	[Keywords] [nvarchar](512) NOT NULL,
	[SearchTime] [datetime] NOT NULL,
	[Lasttime] [datetime] NOT NULL,
	[Frequency] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[IsMemberCreated] [bit] NOT NULL,
 CONSTRAINT [PK_Hishop_Hotkeywords] PRIMARY KEY CLUSTERED 
(
	[Hid] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_ShippingPayment]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_ShippingPayment]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_ShippingPayment](
	[ShippingModeId] [int] NOT NULL,
	[PaymentModeId] [int] NOT NULL,
 CONSTRAINT [PK_Hishop_ShippingPayment] PRIMARY KEY CLUSTERED 
(
	[ShippingModeId] ASC,
	[PaymentModeId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[spf_AgentOrders_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[spf_AgentOrders_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spf_AgentOrders_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@TotalUserOrders int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForUserOrders
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		OrderId nvarchar(50),
		PublishDate datetime
	)	

	INSERT INTO #PageIndexForUserOrders(OrderId,PublishDate)
	Exec sp_executesql @sqlPopulate

	SET @TotalUserOrders = @@rowcount
	
	SELECT  O.*,o.OrderTotal AS OrderPrice,
        (select count(LeaveId) from Hishop_OrderLeaveWords where OrderId = O.OrderId and IsAgentVisited=0 ) as NoVisitNum,
        (select count(LeaveId) from Hishop_OrderLeaveWords where OrderId = O.OrderId ) as VisitNum
	FROM Hishop_Orders O, #PageIndexForUserOrders
	WHERE 
		O.OrderId = #PageIndexForUserOrders.OrderId AND
		#PageIndexForUserOrders.IndexId > @PageLowerBound AND
		#PageIndexForUserOrders.IndexId < @PageUpperBound 
	ORDER BY #PageIndexForUserOrders.IndexId
END' 
END
GO
/****** Object:  Table [dbo].[Hishop_HelpCategories]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_HelpCategories]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_HelpCategories](
	[CategoryId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](100) NOT NULL,
	[DisplaySequence] [int] NOT NULL,
	[IconUrl] [nvarchar](255) NULL,
	[IndexChar] [char](1) NULL,
	[Description] [nvarchar](1000) NULL,
	[IsShowFooter] [bit] NOT NULL,
	[UserId] [int] NOT NULL,
	[IsMemberCreated] [bit] NOT NULL
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_BalanceDrawRequests_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_BalanceDrawRequests_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_BalanceDrawRequests_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@SqlPopulate ntext
)

AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN 
	DECLARE @PageLowerBound int	
	DECLARE @PageUpperBound int
	DECLARE @RowsToReturn int
	DECLARE @TotalBalanceDrawRequest int
	
	SET @TotalBalanceDrawRequest = 0 
	--Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForBalanceDrawRequest
	(
		IndexId int IDENTITY(1,1) NOT NULL,
		JournalNumber bigint
	)

	INSERT INTO #PageIndexForBalanceDrawRequest(JournalNumber)
	EXEC sp_executesql @SqlPopulate

	SET @TotalBalanceDrawRequest = @@rowcount
	
	SELECT 
		B.*,
		(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = B.Applicant) AS UserName		
	FROM
		Hishop_BalanceDrawRequest B (nolock),	
		#PageIndexForBalanceDrawRequest	
	WHERE
		B.JournalNumber = #PageIndexForBalanceDrawRequest.JournalNumber AND
		#PageIndexForBalanceDrawRequest.IndexId > @PageLowerBound AND
		#PageIndexForBalanceDrawRequest.IndexId < @PageUpperBound
	ORDER BY 
		#PageIndexForBalanceDrawRequest.IndexId	
END

--Return the record count
IF (@IsCount = 1)
	SELECT @TotalBalanceDrawRequest' 
END
GO
/****** Object:  Table [dbo].[Hishop_LeaveCommentReplys]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_LeaveCommentReplys]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_LeaveCommentReplys](
	[LeaveId] [bigint] NOT NULL,
	[ReplyId] [bigint] IDENTITY(1,1) NOT NULL,
	[UserId] [int] NOT NULL,
	[ReplyTitle] [nvarchar](100) NOT NULL,
	[ReplyContent] [nvarchar](3000) NOT NULL,
	[ReplyDate] [datetime] NOT NULL,
 CONSTRAINT [PK_Hishop_LeaveCommentReplys] PRIMARY KEY CLUSTERED 
(
	[ReplyId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_UserShippingAddresses]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_UserShippingAddresses]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_UserShippingAddresses](
	[RegionId] [int] NOT NULL,
	[ShippingId] [int] IDENTITY(1,1) NOT NULL,
	[UserId] [int] NOT NULL,
	[ShipTo] [nvarchar](50) NOT NULL,
	[Address] [nvarchar](500) NOT NULL,
	[Zipcode] [nvarchar](20) NOT NULL,
	[EmailAddress] [nvarchar](255) NOT NULL,
	[TelPhone] [nvarchar](20) NULL,
	[CellPhone] [nvarchar](20) NULL,
 CONSTRAINT [PK_Hishop_UserShippingAddresses] PRIMARY KEY CLUSTERED 
(
	[ShippingId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_OrderLeaveWords_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_OrderLeaveWords_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_OrderLeaveWords_Get]
(
 	@PageIndex   INT,
	@PageSize	 INT,
	@IsCount	 BIT,
    @SqlPopulate     NTEXT   
)
as
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn	INT
	DECLARE @TotalRecords	INT
   
	SET @TotalRecords = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForSearch 
	(
		IndexId Bigint IDENTITY (1, 1) NOT NULL,
		LeaveId Bigint,
	)
	
	INSERT INTO #PageIndexForSearch (LeaveId)
	Exec sp_executesql @SqlPopulate
	SET @TotalRecords = @@rowcount
	
	 SELECT
		o.*,(select UserName from vw_Users_FullUser where Hi_UserId=o.userId) as UserName
	FROM 
		Hishop_OrderLeaveWords o (nolock),
		#PageIndexForSearch
	WHERE 
		o.LeaveId = #PageIndexForSearch.LeaveId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
ORDER BY
	#PageIndexForSearch.IndexId
END
	SELECT @TotalRecords' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_GetUserIDByAppToken]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_GetUserIDByAppToken]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_GetUserIDByAppToken]
(
	@AppUserToken varchar(128)
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT
	U.hi_UserId
FROM 
	vw_Users_FullUser U (nolock)
WHERE 
	U.hi_AppUserToken = @AppUserToken' 
END
GO
/****** Object:  Table [dbo].[Hishop_LeaveComments]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_LeaveComments]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_LeaveComments](
	[LeaveId] [bigint] IDENTITY(1,1) NOT NULL,
	[UserId] [int] NULL,
	[AgentId] [int] NULL,
	[UserName] [nvarchar](256) NULL,
	[Title] [nvarchar](100) NOT NULL,
	[PublishContent] [nvarchar](3000) NOT NULL,
	[PublishDate] [datetime] NOT NULL,
	[LastDate] [datetime] NOT NULL,
 CONSTRAINT [PK_Hishop_LeaveComments] PRIMARY KEY CLUSTERED 
(
	[LeaveId] ASC
)
)
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Users_Count_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Users_Count_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Users_Count_Get]
(
	@UsernameFilter nvarchar(128),
	@FilterIncludesEmailAddress bit = 0,
	@UserAccountStatus smallint = 1,
	@IncludeHiddenUsers bit = 0
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

Declare @TotalUsers int

BEGIN

-- Do we need to return a record count?
-- *************************************
  IF ((@UsernameFilter IS NULL) OR (@UsernameFilter = ''''))
    SET @TotalUsers = (SELECT count(hi_UserId) FROM vw_Users_FullUser where (hi_UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1))
  ELSE
    IF (@FilterIncludesEmailAddress = 0)
      SET @TotalUsers = (SELECT count(hi_UserId) FROM vw_Users_FullUser where (hi_UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1) AND UserName LIKE @UsernameFilter)
    ELSE
      SET @TotalUsers = (SELECT count(hi_UserId) FROM vw_Users_FullUser where (hi_UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1) AND (UserName LIKE @UsernameFilter OR Email LIKE @UsernameFilter))



END

SELECT @TotalUsers' 
END
GO
/****** Object:  Table [dbo].[Hishop_OrderRemark]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_OrderRemark]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_OrderRemark](
	[OrderId] [nvarchar](50) NOT NULL,
	[RemarkId] [bigint] IDENTITY(1,1) NOT NULL,
	[UserId] [int] NOT NULL,
	[RemarkDate] [datetime] NOT NULL,
	[Remark] [nvarchar](4000) NOT NULL,
	[LastDate] [datetime] NOT NULL
)
END
GO
/****** Object:  Table [dbo].[Hishop_BalanceDrawRequest]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_BalanceDrawRequest]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_BalanceDrawRequest](
	[JournalNumber] [bigint] IDENTITY(1,1) NOT NULL,
	[RequestTime] [datetime] NOT NULL,
	[Amount] [money] NOT NULL,
	[Applicant] [int] NOT NULL,
	[RequestStatus] [int] NOT NULL,
	[MerchantCode] [nvarchar](300) NOT NULL,
	[Remark] [nvarchar](2000) NULL,
 CONSTRAINT [PK_Hishop_BalanceDrawRequest] PRIMARY KEY CLUSTERED 
(
	[JournalNumber] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_UserProfile]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_UserProfile]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_UserProfile](
	[UserId] [int] NOT NULL,
	[EnableDisplayInMemberList] [smallint] NOT NULL,
	[EnablePrivateMessages] [smallint] NOT NULL,
	[EnableOnlineStatus] [smallint] NOT NULL,
	[EnableEmail] [smallint] NOT NULL,
	[EnableHtmlEmail] [smallint] NOT NULL,
	[IsIgnored] [bit] NOT NULL,
	[MembershipId] [uniqueidentifier] NOT NULL,
	[PropertyNames] [ntext] NULL,
	[PropertyValues] [ntext] NULL,
	[PublicToken] [uniqueidentifier] NOT NULL,
	[OrderNumber] [int] NULL,
	[Expenditure] [money] NOT NULL,
	[EnableTradePassword] [bit] NOT NULL,
	[TradePassword] [nvarchar](128) NULL,
	[TradePasswordSalt] [nvarchar](128) NULL,
	[TradePasswordFormat] [int] NOT NULL,
	[RealName] [nvarchar](50) NULL,
	[Points] [int] NOT NULL,
	[RegionId] [int] NULL,
	[Address] [nvarchar](300) NULL,
	[QQ] [nvarchar](20) NULL,
	[MSN] [nvarchar](20) NULL,
	[TelPhone] [nvarchar](50) NULL,
	[CellPhone] [nvarchar](50) NULL,
	[UserRank] [int] NULL,
	[ParentUserId] [int] NULL,
	[ReferralUserId] [int] NULL,
	[BirthDate] [datetime] NULL,
	[Gender] [int] NULL,
	[Agent_Expires] [datetime] NULL,
	[Agent_IsUrlBindApproved] [bit] NULL,
	[Agent_SiteUrl] [nvarchar](255) NULL,
	[Agent_LogoUrl] [nvarchar](255) NULL,
	[Agent_Footer] [ntext] NULL,
	[Agent_SiteName] [nvarchar](50) NULL,
	[Agent_SiteDescription] [nvarchar](60) NULL,
	[Agent_Theme] [nvarchar](50) NULL,
	[Agent_IsShowTQServer] [bit] NULL,
	[Agent_TQServices] [ntext] NULL,
	[Balance] [money] NULL,
	[DeductMoney] [money] NULL,
 CONSTRAINT [PK_Hishop_UserProfile] PRIMARY KEY CLUSTERED 
(
	[UserId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_OrderOptions]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_OrderOptions]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_OrderOptions](
	[OrderId] [nvarchar](50) NOT NULL,
	[LookupListId] [int] NOT NULL,
	[LookupItemId] [int] NOT NULL,
	[ListDescription] [nvarchar](500) NOT NULL,
	[ItemDescription] [nvarchar](500) NOT NULL,
	[AdjustedPrice] [money] NOT NULL,
	[CustomerTitle] [nvarchar](500) NULL,
	[CustomerDescription] [nvarchar](500) NULL,
 CONSTRAINT [PK_Hishop_OrderOptions] PRIMARY KEY CLUSTERED 
(
	[OrderId] ASC,
	[LookupListId] ASC,
	[LookupItemId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_EmailQueue]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_EmailQueue]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_EmailQueue](
	[EmailId] [uniqueidentifier] NOT NULL,
	[EmailPriority] [int] NOT NULL,
	[IsBodyHtml] [bit] NOT NULL,
	[EmailTo] [nvarchar](2000) NULL,
	[EmailCc] [ntext] NULL,
	[EmailBcc] [ntext] NULL,
	[EmailFrom] [nvarchar](256) NULL,
	[EmailSubject] [nvarchar](1024) NULL,
	[EmailBody] [ntext] NULL,
	[NextTryTime] [datetime] NOT NULL,
	[NumberOfTries] [int] NOT NULL
)
END
GO
/****** Object:  Table [dbo].[Hishop_BalanceFreezeDetails]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_BalanceFreezeDetails]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_BalanceFreezeDetails](
	[JournalNumber] [bigint] IDENTITY(1,1) NOT NULL,
	[FreezeType] [int] NOT NULL,
	[FreezeTime] [datetime] NOT NULL,
	[Amount] [money] NOT NULL,
	[UserId] [int] NOT NULL,
	[Remark] [nvarchar](2000) NULL,
 CONSTRAINT [PK_Hishop_BalanceFreezeDetails] PRIMARY KEY CLUSTERED 
(
	[JournalNumber] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_CouponItems]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_CouponItems]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_CouponItems](
	[CouponId] [int] NOT NULL,
	[ClaimCode] [nvarchar](50) NOT NULL,
	[UserId] [int] NULL,
	[EmailAddress] [nvarchar](255) NULL,
	[GenerateTime] [datetime] NOT NULL,
 CONSTRAINT [PK_Hishop_CouponItems] PRIMARY KEY CLUSTERED 
(
	[ClaimCode] ASC
)
)
END
GO
/****** Object:  Table [dbo].[Hishop_SiteSettings]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[Hishop_SiteSettings]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[Hishop_SiteSettings](
	[SettingsId] [int] IDENTITY(100,1) NOT NULL,
	[Disabled] [bit] NOT NULL,
	[Version] [nvarchar](64) NULL,
	[SettingsXML] [ntext] NULL,
	[SettingsKey] [uniqueidentifier] NULL,
	[ApplicationName] [nvarchar](256) NULL,
 CONSTRAINT [PK_Hishop_SiteSettings] PRIMARY KEY CLUSTERED 
(
	[SettingsId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[aspnet_Roles]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Roles]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[aspnet_Roles](
	[ApplicationId] [uniqueidentifier] NOT NULL,
	[RoleId] [uniqueidentifier] NOT NULL,
	[RoleName] [nvarchar](256) NOT NULL,
	[LoweredRoleName] [nvarchar](256) NOT NULL,
	[Description] [nvarchar](256) NULL,
 CONSTRAINT [PK__aspnet_Roles__2C3393D0] PRIMARY KEY NONCLUSTERED 
(
	[RoleId] ASC
)
)
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[aspnet_Roles]') AND name = N'aspnet_Roles_index1')
CREATE UNIQUE CLUSTERED INDEX [aspnet_Roles_index1] ON [dbo].[aspnet_Roles] 
(
	[ApplicationId] ASC,
	[LoweredRoleName] ASC
)
GO
/****** Object:  Table [dbo].[aspnet_Users]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Users]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[aspnet_Users](
	[ApplicationId] [uniqueidentifier] NOT NULL,
	[UserId] [uniqueidentifier] NOT NULL,
	[UserName] [nvarchar](256) NOT NULL,
	[LoweredUserName] [nvarchar](256) NOT NULL,
	[MobileAlias] [nvarchar](16) NULL,
	[IsAnonymous] [bit] NOT NULL,
	[LastActivityDate] [datetime] NOT NULL,
 CONSTRAINT [PK__aspnet_Users__7D78A4E7] PRIMARY KEY NONCLUSTERED 
(
	[UserId] ASC
)
)
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[aspnet_Users]') AND name = N'aspnet_Users_Index')
CREATE UNIQUE CLUSTERED INDEX [aspnet_Users_Index] ON [dbo].[aspnet_Users] 
(
	[ApplicationId] ASC,
	[LoweredUserName] ASC
)
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[aspnet_Users]') AND name = N'aspnet_Users_Index2')
CREATE NONCLUSTERED INDEX [aspnet_Users_Index2] ON [dbo].[aspnet_Users] 
(
	[ApplicationId] ASC,
	[LastActivityDate] ASC
)
GO
/****** Object:  Table [dbo].[aspnet_Membership]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[aspnet_Membership](
	[ApplicationId] [uniqueidentifier] NOT NULL,
	[UserId] [uniqueidentifier] NOT NULL,
	[Password] [nvarchar](128) NOT NULL,
	[PasswordFormat] [int] NOT NULL,
	[PasswordSalt] [nvarchar](128) NOT NULL,
	[MobilePIN] [nvarchar](16) NULL,
	[Email] [nvarchar](256) NULL,
	[LoweredEmail] [nvarchar](256) NULL,
	[PasswordQuestion] [nvarchar](256) NULL,
	[PasswordAnswer] [nvarchar](128) NULL,
	[IsApproved] [bit] NOT NULL,
	[IsLockedOut] [bit] NOT NULL,
	[CreateDate] [datetime] NOT NULL,
	[LastLoginDate] [datetime] NOT NULL,
	[LastPasswordChangedDate] [datetime] NOT NULL,
	[LastLockoutDate] [datetime] NOT NULL,
	[FailedPasswordAttemptCount] [int] NOT NULL,
	[FailedPasswordAttemptWindowStart] [datetime] NOT NULL,
	[FailedPasswordAnswerAttemptCount] [int] NOT NULL,
	[FailedPasswordAnswerAttemptWindowStart] [datetime] NOT NULL,
	[Comment] [ntext] NULL,
 CONSTRAINT [PK__aspnet_Membershi__0DAF0CB0] PRIMARY KEY NONCLUSTERED 
(
	[UserId] ASC
)
)
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership]') AND name = N'aspnet_Membership_index')
CREATE CLUSTERED INDEX [aspnet_Membership_index] ON [dbo].[aspnet_Membership] 
(
	[ApplicationId] ASC,
	[LoweredEmail] ASC
)
GO
/****** Object:  Table [dbo].[aspnet_Profile]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Profile]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[aspnet_Profile](
	[UserId] [uniqueidentifier] NOT NULL,
	[PropertyNames] [ntext] NOT NULL,
	[PropertyValuesString] [ntext] NOT NULL,
	[PropertyValuesBinary] [image] NOT NULL,
	[LastUpdatedDate] [datetime] NOT NULL,
 CONSTRAINT [PK__aspnet_Profile__22AA2996] PRIMARY KEY CLUSTERED 
(
	[UserId] ASC
)
)
END
GO
/****** Object:  Table [dbo].[aspnet_UsersInRoles]    Script Date: 04/20/2009 16:21:45 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_UsersInRoles]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[aspnet_UsersInRoles](
	[UserId] [uniqueidentifier] NOT NULL,
	[RoleId] [uniqueidentifier] NOT NULL,
 CONSTRAINT [PK__aspnet_UsersInRo__300424B4] PRIMARY KEY CLUSTERED 
(
	[UserId] ASC,
	[RoleId] ASC
)
)
END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[aspnet_UsersInRoles]') AND name = N'aspnet_UsersInRoles_index')
CREATE NONCLUSTERED INDEX [aspnet_UsersInRoles_index] ON [dbo].[aspnet_UsersInRoles] 
(
	[RoleId] ASC
)
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_ConsultationsAndReplys_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_ConsultationsAndReplys_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_ConsultationsAndReplys_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@Total int = 0 output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForReviews
	(
		[IndexId] int IDENTITY (1, 1) NOT NULL,
		[ConsultationId] int
	)	

	INSERT INTO #PageIndexForReviews (ConsultationId) 
    Exec sp_executesql @sqlPopulate

	SET @Total = @@rowcount

	-- 评论记录
	SELECT pr.ConsultationId,pr.ProductId,pr.ConsultationText,pr.ConsultationDate,
		#PageIndexForReviews.IndexId,pr.UserName,pr.UserId,
		(select ThumbnailsUrl from Hishop_Products where ProductId = pr.ProductId) as ThumbnailsUrl,
		(select ProductName from Hishop_Products where ProductId = pr.ProductId) as ProductName,
		(SELECT Name FROM Hishop_UserRanks 
		 WHERE RankId = (SELECT UserRank FROM Hishop_UserProfile 
						 WHERE UserId = pr.UserId ) ) AS RankName	-- 用户等级	
	FROM Hishop_ProductConsultations pr, #PageIndexForReviews
	WHERE  
		pr.ConsultationId = #PageIndexForReviews.ConsultationId AND
		#PageIndexForReviews.IndexId > @PageLowerBound AND
		#PageIndexForReviews.IndexId < @PageUpperBound 
	ORDER BY ReplyDate DESC


	-- 回复记录
	SELECT ConsultationId,ReplyText,ReplyDate 
		--(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = pc.ReplyUserId) AS ReplyUserName, --用户名
		--(SELECT Name FROM Hishop_MemberRanks 
		 --WHERE RankId = (SELECT UserRank FROM vw_Users_FullUser 
						 --WHERE hi_UserId = pc.ReplyUserId ) ) AS ReplyRankName -- 用户等级	
	FROM Hishop_ProductConsultations pc
	ORDER BY ReplyDate DESC	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_ProductBrowse_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_ProductBrowse_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_ProductBrowse_Get]
	(
		@ProductId INT,
		@RankId INT = 0
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	-- 更新浏览次数，如果不是在商品详细页使用这个存储过程，要仔细考虑这条语句
        UPDATE Hishop_Products SET VistiCounts = VistiCounts + 1 WHERE ProductId =@ProductId
	
	if @RankId = 0
	BEGIN
		-- 基本信息
		SELECT c.Name, p.*, p.SalePrice AS RankPrice FROM Hishop_Products p LEFT OUTER  JOIN Hishop_Categories c ON p.CategoryId = c.CategoryId WHERE p.ProductId = @ProductId
		--SKU
		SELECT * FROM Hishop_SKUs WHERE ProductId = @ProductId
		-- 属性
		SELECT AttributeName, ValueStr FROM Hishop_ProductAttributes pa JOIN Hishop_Attributes a ON pa.AttributeId = a.AttributeId WHERE ProductId = @ProductId ORDER BY DisplaySequence
		--多图
		SELECT ImageUrl FROM Hishop_ProductImages WHERE ProductId = @ProductId
		-- 配件
		SELECT p.ProductName, s.SKU, s.ProductId, s.Stock, s.AttributeNames, s.AttributeValues, ISNULL(s.Price,0) + p.SalePrice AS RankPrice
		FROM Hishop_ProductAccessories pa JOIN Hishop_SKUs s ON pa.ProductAccessoriesSKU = s.SKU JOIN Hishop_Products p ON s.ProductId = p.ProductId WHERE pa.ProductId = @ProductId AND p.Upselling = 1
		-- 相关商品
		SELECT p.*,  p.SalePrice AS RankPrice FROM Hishop_RelatedProducts r JOIN Hishop_Products p ON r.RelatedProductId = p.ProductId WHERE r.ProductId = @ProductId  AND p.Upselling = 1
	END
	
	else
	
	BEGIN
		-- 基本信息
		SELECT c.Name, p.*, ISNULL(pp.SalePrice, p.SalePrice) AS RankPrice 
		FROM Hishop_Products p LEFT OUTER JOIN Hishop_ProductPrices pp ON p.ProductId = pp.ProductId AND pp.RankId = @RankId LEFT OUTER JOIN Hishop_Categories c ON p.CategoryId = c.CategoryId
		 WHERE p.ProductId = @ProductId
		--SKU
		SELECT * FROM Hishop_SKUs WHERE ProductId = @ProductId
		-- 属性
		SELECT AttributeName, ValueStr FROM Hishop_ProductAttributes pa JOIN Hishop_Attributes a ON pa.AttributeId = a.AttributeId WHERE ProductId = @ProductId ORDER BY DisplaySequence
		--多图
		SELECT ImageUrl FROM Hishop_ProductImages WHERE ProductId = @ProductId
		-- 配件
		SELECT p.ProductName, s.SKU, s.ProductId, s.Stock, s.AttributeNames, s.AttributeValues, ISNULL(s.Price,0) + ISNULL(pp.SalePrice, p.SalePrice) AS RankPrice
		FROM Hishop_ProductAccessories pa join Hishop_Products p ON pa.ProductAccessoriesId = p.ProductId LEFT OUTER join Hishop_ProductPrices pp ON p.ProductId = pp.ProductId  AND pp.RankId = @RankId
		join Hishop_SKUs s ON pa.ProductAccessoriesSKU = s.SKU 
		WHERE pa.ProductId = @ProductId AND p.Upselling = 1
		-- 相关商品
		SELECT p.*, ISNULL(pp.SalePrice, p.SalePrice) AS RankPrice 
		FROM Hishop_RelatedProducts r JOIN Hishop_Products p ON r.RelatedProductId = p.ProductId LEFT OUTER JOIN Hishop_ProductPrices pp ON p.ProductId = pp.ProductId AND pp.RankId = @RankId 
		 WHERE r.ProductId = @ProductId AND p.Upselling = 1
	END
	-- 商品咨询
	SELECT * FROM Hishop_ProductConsultations WHERE ProductId = @ProductId 
	-- 商品评论
	SELECT * FROM Hishop_ProductReviews WHERE ProductId = @ProductId 
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spb_ConsultationsReplyed_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[spb_ConsultationsReplyed_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spb_ConsultationsReplyed_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@Total int = 0 output,
	@sqlPopulate ntext
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1


	CREATE TABLE #PageIndexForConsultation
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		ProductId int
	)	

	INSERT INTO #PageIndexForConsultation(ProductId)
	Exec sp_executesql @sqlPopulate

	SELECT pt.ProductId,
		(SELECT TOP 1 ReplyDate FROM Hishop_ProductConsultations WHERE ProductId = pt.ProductId ORDER BY ReplyDate desc) AS Replydate,
		(SELECT ProductName FROM Hishop_Products WHERE ProductId = pt.ProductId) AS ProductName,
		(SELECT AuctionType FROM Hishop_Products WHERE ProductId = pt.ProductId) AS AuctionType
	FROM Hishop_ProductConsultations pt,#PageIndexForConsultation
	WHERE 
		pt.ProductId IN (SELECT ProductId FROM #PageIndexForConsultation ) AND
		#PageIndexForConsultation.IndexId > @PageLowerBound AND
		#PageIndexForConsultation.IndexId < @PageUpperBound 
		GROUP BY pt.ProductId
		ORDER BY Replydate DESC

	SET @Total = @@rowcount	

    SELECT ConsultationId,ProductId,ConsultationText,ConsultationDate,ReplyText,UserName,UserId,ReplyUserId,
        (SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = Hishop_ProductConsultations.ReplyUserId) AS ReplyUserName 
    FROM Hishop_ProductConsultations 
	WHERE ReplyText IS NOT NULL
	ORDER BY Replydate DESC
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_UnRegisterSchemaVersion]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_UnRegisterSchemaVersion]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_UnRegisterSchemaVersion]
    @Feature                   nvarchar(128),
    @CompatibleSchemaVersion   nvarchar(128)
AS
BEGIN
    DELETE FROM dbo.aspnet_SchemaVersions
        WHERE   Feature = LOWER(@Feature) AND @CompatibleSchemaVersion = CompatibleSchemaVersion
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_CheckSchemaVersion]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_CheckSchemaVersion]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_CheckSchemaVersion]
    @Feature                   nvarchar(128),
    @CompatibleSchemaVersion   nvarchar(128)
AS
BEGIN
    IF (EXISTS( SELECT  *
                FROM    dbo.aspnet_SchemaVersions
                WHERE   Feature = LOWER( @Feature ) AND
                        CompatibleSchemaVersion = @CompatibleSchemaVersion ))
        RETURN 0

    RETURN 1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_RegisterSchemaVersion]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_RegisterSchemaVersion]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_RegisterSchemaVersion]
    @Feature                   nvarchar(128),
    @CompatibleSchemaVersion   nvarchar(128),
    @IsCurrentVersion          bit,
    @RemoveIncompatibleSchema  bit
AS
BEGIN
    IF( @RemoveIncompatibleSchema = 1 )
    BEGIN
        DELETE FROM dbo.aspnet_SchemaVersions WHERE Feature = LOWER( @Feature )
    END
    ELSE
    BEGIN
        IF( @IsCurrentVersion = 1 )
        BEGIN
            UPDATE dbo.aspnet_SchemaVersions
            SET IsCurrentVersion = 0
            WHERE Feature = LOWER( @Feature )
        END
    END

    INSERT  dbo.aspnet_SchemaVersions( Feature, CompatibleSchemaVersion, IsCurrentVersion )
    VALUES( LOWER( @Feature ), @CompatibleSchemaVersion, @IsCurrentVersion )
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_BannedNetwork_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_BannedNetwork_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_BannedNetwork_CreateUpdateDelete]
	@BannedNetworkID	INT = 0 OUTPUT,
	@StartingAddress	NVARCHAR(50)=  null,
	@EndingAddress		NVARCHAR(50) = null,
	@BannedDate			DATETIME,
	@ActionType			INT
AS
	DECLARE @ID INT
	DECLARE @ERROR INT
	DECLARE @ROWCOUNT INT
	
	-- CREATE
	IF @ActionType = 0 
	BEGIN
		IF EXISTS( SELECT * FROM Hishop_BannedNetworks where BannedNetworkID = @BannedNetworkID )
			exec sp_cg_BannedNetwork_CreateUpdateDelete @BannedNetworkID OUTPUT, @StartingAddress, @EndingAddress, @BannedDate, 1 
		ELSE
		BEGIN
		
			INSERT INTO Hishop_BannedNetworks (
				StartingAddress,
				EndingAddress,
				BannedDate
			) VALUES( 
				@StartingAddress,
				@EndingAddress,
				@BannedDate
			)

			SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR( ''An error occurred while trying to create a new cs_BannedNetwork record.'', 16, 1 )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				SET @BannedNetworkID = @ID
				RETURN 0
			END
		END
	END
	ELSE IF( @ActionType = 1 )
	BEGIN
		-- UPDATE
		IF NOT EXISTS( SELECT * FROM Hishop_BannedNetworks WHERE BannedNetworkID = @BannedNetworkID )
			exec sp_cg_BannedNetwork_CreateUpdateDelete @BannedNetworkID OUTPUT, @StartingAddress, @EndingAddress, @BannedDate, 0 
		ELSE
		BEGIN
			UPDATE Hishop_BannedNetworks SET
				StartingAddress	= @StartingAddress,
				EndingAddress	= @EndingAddress,
				BannedDate		= @BannedDate
			WHERE
				BannedNetworkID = @BannedNetworkID
				
			SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR(''Could not update the Hishop_BannedNetworks record for BannedNetworkID %d'', 16, 1, @BannedNetworkID )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0				
			END
		END
	END
	ELSE IF( @ActionType = 2 )
	BEGIN
		-- DELETE
		DELETE Hishop_BannedNetworks
		WHERE BannedNetworkID = @BannedNetworkID
			
		SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
		IF( @ROWCOUNT = 1 )
			RETURN 0
		ELSE
			RETURN 1
		
	END
	ELSE
	BEGIN
		RAISERROR( ''The ActionType value should be between 0 and 2. The value of %d was not within this range'', 16, 1, @ActionType )
		RETURN 1
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_BannedNetworks_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_BannedNetworks_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_BannedNetworks_Get]

AS
	SELECT
		  BannedNetworkID
		, StartingAddress
		, EndingAddress
		, BannedDate
	FROM Hishop_BannedNetworks' 
END
GO
/****** Object:  StoredProcedure [dbo].[spb_ProductNotify]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[spb_ProductNotify]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spb_ProductNotify]
 (
	 @ProductId int
)
as
Begin
	SELECT Email FROM Hishop_ProductNotify
	Where ProductId = @ProductId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ca_Promote_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ca_Promote_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ca_Promote_Get]
(
    @ActivityId INT
)
AS
  DECLARE @PromoteType INT

  SELECT @PromoteType = PromoteType FROM Hishop_PromoteSales 
		WHERE ActivityId = @ActivityId

	IF @PromoteType IS NULL
		RETURN
	/*
		满额赠送--1
		满额打折--2
		满额免费用--3
		买几送几--4
		满量打折--5
	*/
	--基本信息
	SELECT * FROM Hishop_PromoteSales WHERE ActivityId=@ActivityId
	
	-- 根据@PromoteType返回具体信息
	IF @PromoteType=1
	BEGIN
		SELECT * FROM Hishop_PromoteSales_Present WHERE ActivityId=@ActivityId
		RETURN
	END
	
	IF @PromoteType=2
	BEGIN
		SELECT * FROM Hishop_PromoteSales_Discount WHERE ActivityId=@ActivityId
		RETURN
	END

	IF @PromoteType=3
	BEGIN
		SELECT * FROM Hishop_PromoteSales_Fee WHERE ActivityId=@ActivityId
		RETURN
	END

	IF @PromoteType=4
	BEGIN
		SELECT * FROM Hishop_PromoteSales_Give WHERE ActivityId=@ActivityId
		RETURN
	END

	IF @PromoteType=5
	BEGIN
		SELECT * FROM Hishop_PromoteSales_QuantityDiscount WHERE ActivityId=@ActivityId
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ca_Promote_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ca_Promote_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ca_Promote_CreateUpdateDelete] 
	(
		@ActivityId INT = NULL OUTPUT,
		@Name NVARCHAR(100) = NULL,
		@PromoteType INT = NULL,
		@Description NTEXT = NULL,
		@StartTime DATETIME = NULL,
		@ClosingTime DATETIME = NULL,
		@Action INT,
		@Status INT OUTPUT
	)

AS
	SET @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN -- 同时删除具体类型的优惠活动
	
		SET XACT_ABORT ON
		DECLARE @intErrorCode INT
		
		BEGIN TRAN
		
		DELETE FROM Hishop_PromoteSales_Products WHERE ActivityId = @ActivityId
		SET @intErrorCode = @@ERROR
		
		IF @intErrorCode = 0
		BEGIN
			DELETE FROM Hishop_PromoteSales_Give WHERE ActivityId = @ActivityId
			SET @intErrorCode = @@ERROR
		END
		
		IF @intErrorCode = 0
		BEGIN
			DELETE FROM Hishop_PromoteSales_Discount WHERE ActivityId = @ActivityId
			SET @intErrorCode = @@ERROR
		END
		
		IF @intErrorCode = 0
		BEGIN
			DELETE FROM Hishop_PromoteSales_Fee WHERE ActivityId = @ActivityId
			SET @intErrorCode = @@ERROR
		END
		
		IF @intErrorCode = 0
		BEGIN
			DELETE FROM Hishop_PromoteSales_Gifts WHERE ActivityId = @ActivityId
			SET @intErrorCode = @@ERROR
		END
		
		IF @intErrorCode = 0
		BEGIN
			DELETE FROM Hishop_PromoteSales_Present WHERE ActivityId = @ActivityId
			SET @intErrorCode = @@ERROR
		END
		
		IF @intErrorCode = 0
		BEGIN
			DELETE FROM Hishop_PromoteSales WHERE ActivityId = @ActivityId
			SET @intErrorCode = @@ERROR
		END
			
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
			COMMIT TRAN
		END
		ELSE
			ROLLBACK TRAN
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN
		
		INSERT INTO 
			Hishop_PromoteSales([Name], PromoteType, Description, StartTime, ClosingTime)
		VALUES 
			(@Name, @PromoteType, @Description, @StartTime, @ClosingTime)
			
		SET @ActivityId = @@IDENTITY
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
		UPDATE 
			Hishop_PromoteSales 
		SET 
			[Name] = @Name, 
			Description = @Description, 
			StartTime = @StartTime,
			ClosingTime = @ClosingTime
		WHERE ActivityId = @ActivityId
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_FeeFree_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_FeeFree_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_FeeFree_Get]
(
  @DateTime DateTime
)
as
BEGIN
	SELECT ps.*, pf.Amount,Pf.ShipChargeFree,pf.ServiceChargefree,pf.PackingChargeFree From Hishop_PromoteSales ps 
					  INNER JOIN Hishop_PromoteSales_Fee  pf  ON ps.ActivityId = pf.ActivityId 
	Where ps.ClosingTime >@DateTime AND ps.StartTime<@DateTime Order by Amount DESC

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_ProductPrices_Set]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_ProductPrices_Set]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_ProductPrices_Set]
	(
		@RankId INT,
		@ProductId INT,
		@SalePrice MONEY = 0
	)

AS

	IF @SalePrice <= 0
	BEGIN
		DELETE FROM Hishop_ProductPrices WHERE RankId = @RankId AND ProductId = @ProductId
		RETURN
	END
	
	IF EXISTS(SELECT SalePrice FROM Hishop_ProductPrices WHERE RankId = @RankId AND ProductId = @ProductId)
		UPDATE 
			Hishop_ProductPrices 
		SET 
			SalePrice = @SalePrice
		WHERE RankId = @RankId AND ProductId = @ProductId
	ELSE
		INSERT INTO 
			Hishop_ProductPrices(RankId, ProductId, SalePrice)
		VALUES 
			(@RankId, @ProductId, @SalePrice)' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_UserRank_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_UserRank_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_UserRank_CreateUpdateDelete] 
	(
		@RankId INT = NULL,
		@Name NVARCHAR(50) = NULL,
		@Description NVARCHAR(200) = NULL,
		@Point INT = NULL,
		@IsDefault BIT = NULL,
		@IsAgentRank BIT = NULL,
		@NumberOfMemberRanks INT = NULL,
		@IsMemberCreated BIT = NULL,
		@CreatorUserId INT = NULL,
		@PriceType NVARCHAR(20) = NULL,
		@PriceOperations NVARCHAR(10) = NULL,
		@PriceValue MONEY = NULL,
		@SqlPopulate NTEXT = NULL,
		@Action INT,
		@Status INT OUTPUT
	)
AS
	SET @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN
	
		-- 默认等级或有用户的等级不能删除
		IF @IsDefault=1 OR EXISTS(SELECT UserId FROM Hishop_UserProfile WHERE UserRank = @RankId)
		BEGIN
			RETURN
		END
		
		DELETE FROM Hishop_UserRanks WHERE RankId = @RankId
		IF @@ROWCOUNT > 0
		BEGIN
			SET @Status = 0
			DELETE FROM Hishop_ProductPrices WHERE RankId = @RankId	
		END
		RETURN
	END
	
	CREATE TABLE #Price
	(
		ProductId INT,
		SalePrice money
	)
		 
	INSERT #Price (ProductId, SalePrice) EXEC(@SqlPopulate) 
	
	IF @Action = 0 -- 创建
	BEGIN
		IF 	@IsDefault=1 --默认会员
		BEGIN
			IF @IsMemberCreated=0
				UPDATE Hishop_UserRanks SET IsDefault = 0 WHERE IsMemberCreated = 0 
			ELSE
				UPDATE Hishop_UserRanks SET IsDefault = 0 WHERE IsMemberCreated = 1 AND CreatorUserId = @CreatorUserId
		END	
		INSERT INTO Hishop_UserRanks([Name], Description, Point, IsDefault, IsAgentRank, NumberOfMemberRanks, IsMemberCreated, CreatorUserId, PriceType, PriceOperations, PriceValue) 
		VALUES (@Name, @Description, @Point, @IsDefault, @IsAgentRank, @NumberOfMemberRanks, @IsMemberCreated,@CreatorUserId, @PriceType, @PriceOperations, @PriceValue) 
		IF @@ROWCOUNT > 0
		BEGIN
			SET @RankId = @@identity
			SET @Status = 0
			INSERT INTO Hishop_ProductPrices(RankId, ProductId, SalePrice) SELECT @RankId, ProductId, SalePrice FROM #Price 	
		END	
		RETURN
	END

	IF @Action = 1 -- 修改价格公式及价格
	BEGIN
		UPDATE Hishop_UserRanks SET 
			PriceType = @PriceType, 
			PriceOperations = @PriceOperations,
			PriceValue = @PriceValue
		WHERE 
			RankId = @RankId
		IF @@ROWCOUNT > 0
		BEGIN
			SET @Status = 0
			DELETE FROM Hishop_ProductPrices WHERE RankId = @RankId		
			INSERT INTO Hishop_ProductPrices(RankId, ProductId, SalePrice) SELECT @RankId, ProductId, SalePrice FROM #Price 	
		END
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_ProductPrices_ReSet]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_ProductPrices_ReSet]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_ProductPrices_ReSet]
	(
		@CategoryId INT
	)

AS

delete from Hishop_ProductPrices where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))

declare @RankId int
declare @PriceType nvarchar(20)
declare @PriceOperations nvarchar(10)
declare @PriceValue money

declare userRanks_cursor Cursor for select RankId, PriceType, PriceOperations, PriceValue from Hishop_UserRanks
open userRanks_cursor

Fetch next from userRanks_cursor into @RankId, @PriceType, @PriceOperations, @PriceValue
while @@fetch_status = 0
begin 
	Fetch next from userRanks_cursor into @RankId, @PriceType, @PriceOperations, @PriceValue
	
	if @PriceOperations = ''+''
	begin
		if @PriceType = ''SalePrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, SalePrice + @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
		continue
		if @PriceType = ''MarketPrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, MarketPrice + @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
		continue
		if @PriceType = ''CostPrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, CostPrice + @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
	end
	continue	

	if  @PriceOperations = ''-''
	begin
		if @PriceType = ''SalePrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, SalePrice - @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
		continue
		if @PriceType = ''MarketPrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, MarketPrice - @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
		continue
		if @PriceType = ''CostPrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, CostPrice - @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
	end
	continue

	if @PriceOperations = ''*''
	begin
		if @PriceType = ''SalePrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, SalePrice * @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
		continue
		if @PriceType = ''MarketPrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, MarketPrice * @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
		continue
		if @PriceType = ''CostPrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, CostPrice * @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
	end
	continue
	
	if @PriceOperations = ''/''
	begin
		if @PriceType = ''SalePrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, SalePrice / @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
		continue
		if @PriceType = ''MarketPrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, MarketPrice / @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
		continue
		if @PriceType = ''CostPrice''
		begin
			insert into Hishop_ProductPrices (RankId, ProductId, SalePrice) select @RankId, ProductId, CostPrice / @PriceValue
			from Hishop_Products where ProductId in (select ProductId from Hishop_Products where CategoryId = @CategoryId OR CategoryId IN (SELECT CategoryId FROM Hishop_Categories WHERE [Path] LIKE +''%''+str(@CategoryId)+''|%''))
		end
	end
end
close userRanks_cursor   
deallocate userRanks_cursor' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_co_Order_UserPay]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_co_Order_UserPay]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_co_Order_UserPay]
(
	@OrderId nvarchar(50),
	@UserId int,
	@Username nvarchar(256),
	@ActionCode nvarchar(100),
	@ChangeDate DateTime,
	@Expenses money,
	@Balance money,
	@Status INT = 99 OUTPUT 
)
AS

DECLARE @intErrorCode int
SET @intErrorCode = 0

SET XACT_ABORT ON

BEGIN TRAN
	UPDATE Hishop_Orders SET PaymentStatus = 1 WHERE OrderId = @OrderId
	SET @intErrorCode = @@rowcount
	
	IF @intErrorCode = 1
	BEGIN
		INSERT INTO Hishop_OrderActionHistorys(OrderId, UserId, Username, ActionCode, ActionDate)
			VALUES(@OrderId, @UserId, @Username, @ActionCode, @ChangeDate)
		SET @intErrorCode = @@rowcount
	END
	IF @intErrorCode = 1
	BEGIN
		INSERT INTO Hishop_BalanceDetails(UserId, TradeDate, TradeType, Expenses, Balance, Payer)
			VALUES(@UserId, @ChangeDate, 6, @Expenses, @Balance, @UserId)
		SET @intErrorCode = @@rowcount
	END
	IF (@intErrorCode = 1)
	BEGIN
		SET @Status = 0
		COMMIT TRAN
	END
	ELSE
		ROLLBACK TRAN' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_co_Order_UserOption]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_co_Order_UserOption]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_co_Order_UserOption]
(
	@OrderId nvarchar(50),
	@UserId int,
	@Username nvarchar(256),
	@ActionCode nvarchar(100),
	@ChangeDate DateTime,
	@RefundStatus int,
	@ShippingStatus int,
	@PaymentStatus int,
	@ActivityStatus int
)
AS
		INSERT INTO Hishop_OrderActionHistorys(OrderId, UserId, Username, ActionCode, ActionDate)
			VALUES(@OrderId, @UserId, @Username, @ActionCode, @ChangeDate)
			
		UPDATE Hishop_Orders 
		SET RefundStatus = @RefundStatus, ShippingStatus = @ShippingStatus, PaymentStatus = @PaymentStatus, ActivityStatus = @ActivityStatus 
		WHERE OrderId = @OrderId' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_co_Order_Option]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_co_Order_Option]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_co_Order_Option]
(
	@OrderId nvarchar(50),
	@UserId int,
	@Username nvarchar(256),
	@ActionCode nvarchar(100),
	@ChangeDate datetime,
	@RefundStatus int,
	@ShippingStatus int,
	@PaymentStatus int,
	@ActivityStatus int
)
AS
		INSERT INTO Hishop_OrderActionHistorys(OrderId, UserId, Username, ActionCode, ActionDate)
			VALUES(@OrderId, @UserId, @Username, @ActionCode, @ChangeDate)
			
		UPDATE Hishop_Orders 
		SET RefundStatus = @RefundStatus, ShippingStatus = @ShippingStatus, PaymentStatus = @PaymentStatus, ActivityStatus = @ActivityStatus 
		WHERE OrderId = @OrderId' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Order_Delete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Order_Delete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Order_Delete]
	(
		@OrderId nvarchar(50),
		@Status INT OUTPUT
	)
AS	

	DECLARE @intErrorCode INT

	-- 初始化信息
	SELECT @Status = 99, @intErrorCode = 0
		
	SET XACT_ABORT ON
	
	BEGIN TRAN

    -- 订单操作记录
    DELETE FROM Hishop_OrderActionHistorys Where OrderId=@OrderId
	SET @intErrorCode = @intErrorCode + @@ERROR

    -- 订单退款记录
    DELETE FROM Hishop_RefundOrders Where OrderId=@OrderId
	SET @intErrorCode = @intErrorCode + @@ERROR

    -- 订单项
 	DELETE FROM Hishop_OrderItems WHERE OrderId=@OrderId
	SET @intErrorCode = @intErrorCode + @@ERROR
		
    -- 订单选项
 	DELETE FROM Hishop_OrderOptions WHERE OrderId=@OrderId
	SET @intErrorCode = @intErrorCode + @@ERROR

    -- 礼品
 	DELETE FROM Hishop_OrderGifts WHERE OrderId=@OrderId
	SET @intErrorCode = @intErrorCode + @@ERROR
	
    -- 订单留言
 	DELETE FROM Hishop_OrderLeaveWords WHERE OrderId=@OrderId
	SET @intErrorCode = @intErrorCode + @@ERROR
	
    -- 订单备注
 	DELETE FROM Hishop_OrderRemark WHERE OrderId=@OrderId
	SET @intErrorCode = @intErrorCode + @@ERROR
	
    -- 定单表
 	DELETE FROM Hishop_Orders WHERE OrderId=@OrderId
	SET @intErrorCode = @intErrorCode + @@ERROR

	IF @intErrorCode = 0
	BEGIN		
		SET @Status = 0
		COMMIT TRAN
	END
	ELSE
		ROLLBACK TRAN	
	RETURN' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_InpourRequest_Create]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_InpourRequest_Create]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_InpourRequest_Create]
	(
		@InpourId bigint OUTPUT,
		@TradeDate DATETIME,
		@InpourBlance MONEY,
		@UserId INT,
		@PaymentGateway NVARCHAR(50),
		@Status INT OUTPUT
	)
AS
	SET @Status = 99

	-- 添加一条预付款充值记录	
	BEGIN
		INSERT INTO Hishop_InpourRequest VALUES(@TradeDate,@InpourBlance,@UserId,@PaymentGateway)
		
		IF @@ROWCOUNT = 1
			SELECT @InpourId = @@IDENTITY
			SET @Status = 0	 
	
		SET IDENTITY_INSERT Hishop_InpourRequest OFF 
		   
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_BalanceDetails_Create]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_BalanceDetails_Create]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_BalanceDetails_Create]	
(
	@UserId INT,
	@TradeDate DATETIME,
	@TradeType INT,
	@Income MONEY,
	@Balance MONEY,
	@Remark NVARCHAR(2000),
	@InpourId bigint,
	@Status INT OUTPUT
)
AS
	SELECT @Status = 99
	BEGIN
		SET XACT_ABORT ON
		DECLARE @intErrorCode INT
		
		BEGIN TRAN
		-- 添加一条预付款明细
		INSERT INTO 
			Hishop_BalanceDetails (UserId, TradeDate, TradeType, Income, Balance, Remark) 
		VALUES
			(@UserId, @TradeDate, @TradeType, @Income, @Balance, @Remark)
	    --更新个人信息的预付款记录
        update Hishop_UserProfile set balance=@Balance where UserId=@UserId
		SET @intErrorCode = @@RowCount
		
		IF @intErrorCode = 1
		BEGIN
			-- 删除一条充值记录
			DELETE FROM Hishop_InpourRequest WHERE InpourId = @InpourId
			SET @intErrorCode = @intErrorCode + @@RowCount
		END
		
		IF @intErrorCode = 2
		BEGIN
			SET @Status = 0
			COMMIT TRAN
		END
		ELSE
			ROLLBACK TRAN
			
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_InpourRequest_Delete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_InpourRequest_Delete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_InpourRequest_Delete]
(	
	@InpourId bigint,
	@Status INT OUTPUT
	)
AS
    SET @Status = 99
    -- 删除一条预付款充值记录
    BEGIN
		DELETE FROM Hishop_InpourRequest WHERE InpourId = @InpourId
		IF @@ROWCOUNT = 1			
			SET @Status = 0
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_AgentBalaneToMember]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_AgentBalaneToMember]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_AgentBalaneToMember]
(
	@AgentId int,
	@AgentExpenses money,
	@AgentBalance money,
	@MemberId int,
	@MemberIncome money,
	@MemberBalance money,
	@ChangeDate DateTime,
	@Remark nvarchar(100),
	@Status INT = 99 OUTPUT 
)
AS

DECLARE @intErrorCode int
SET @intErrorCode = 0

SET XACT_ABORT ON

BEGIN TRAN
	INSERT INTO Hishop_BalanceDetails(UserId, TradeDate, TradeType, Expenses, Balance, Payer, Payee, Remark)
		VALUES(@AgentId, @ChangeDate, 6, @AgentExpenses, @AgentBalance, @AgentId, @MemberId, @Remark)
	SET @intErrorCode = @@rowcount
	update Hishop_UserProfile set balance=@AgentBalance where UserId=@AgentId
	IF (@intErrorCode = 1)
	BEGIN 
		INSERT INTO Hishop_BalanceDetails(UserId, TradeDate, TradeType, Income, Balance, Payer, Payee, Remark)
			VALUES(@MemberId, @ChangeDate, 6, @MemberIncome, @MemberBalance, @AgentId, @MemberId, @Remark)
		SET @intErrorCode = @@rowcount
		update Hishop_UserProfile set balance=@MemberBalance where UserId=@MemberId
	END
	IF (@intErrorCode = 1)
	BEGIN
		SET @Status = 0
		COMMIT TRAN
	END
	ELSE
		ROLLBACK TRAN' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_BalanceDrawRequest_Update]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_BalanceDrawRequest_Update]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_BalanceDrawRequest_Update]
(
	@JournalNumber bigint,
	@RequestStatus int,
	@Status INT = 0 OUTPUT 
)
AS

DECLARE @intErrorCode int
DECLARE @OldBalance money
DECLARE @NewBalance money

DECLARE @DealTime datetime
DECLARE @DealAmount money
DECLARE @UserId int

SELECT 
	@Status = 99, @intErrorCode = 0, @DealTime = RequestTime, @DealAmount = Amount, @UserId = Applicant
FROM Hishop_BalanceDrawRequest WHERE JournalNumber = @JournalNumber

SET XACT_ABORT ON

BEGIN TRAN
	-- 更改提现申请状态
	IF @intErrorCode = 0
	BEGIN
		UPDATE Hishop_BalanceDrawRequest  SET RequestStatus = @RequestStatus WHERE  JournalNumber = @JournalNumber 
		SET @intErrorCode = @intErrorCode + @@rowcount
	END
	
	-- 删除冻结金额信息
	IF @intErrorCode = 1
	BEGIN
		DELETE FROM Hishop_BalanceFreezeDetails WHERE FreezeTime = @DealTime AND Amount = @DealAmount AND UserId = @UserId 
		SET @intErrorCode = @intErrorCode + @@rowcount
	END
	
	-- 添加相应的预付款明细记录
	IF @intErrorCode = 2 AND @RequestStatus = 2 
	BEGIN
		SELECT @OldBalance = Balance FROM Hishop_UserProfile WHERE UserId = @UserId 
		SET @NewBalance = @OldBalance - @DealAmount
		
		INSERT INTO Hishop_BalanceDetails (UserId, TradeDate, TradeType, Expenses, Balance)
		VALUES (@UserId, getdate(), 7, @DealAmount, @NewBalance)
		SET @intErrorCode = @intErrorCode + @@rowcount

        update Hishop_UserProfile set balance=@NewBalance where UserId=@UserId
	END
	
	IF ((@RequestStatus = 2 AND @intErrorCode=3) OR (@RequestStatus = 3 AND @intErrorCode = 2))
	BEGIN
		SET @Status = 0
		COMMIT TRAN
	END
	ELSE
		ROLLBACK TRAN' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_AccountSummary_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_AccountSummary_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_AccountSummary_Get]
(
	@UserId INT
)
AS

	-- 定义账户查询临时表
	CREATE TABLE #tbBalances (IndexId INT IDENTITY (1, 1) NOT NULL,UserId INT, AccountAmount MONEY , FreezeBalance MONEY)
	DECLARE @AccountAmount money, @FreezeBalance money
	BEGIN	
		-- 获取该用户的冻结金额 
		SELECT @FreezeBalance = SUM(Amount) FROM Hishop_BalanceFreezeDetails WHERE UserId=@UserId
		-- 预付款总额
		SELECT TOP 1 @AccountAmount = Balance FROM Hishop_BalanceDetails WHERE UserId= @UserId ORDER BY JournalNumber DESC
		-- 插入临时表
		INSERT INTO #tbBalances(UserId, AccountAmount,FreezeBalance) VALUES(@UserId, @AccountAmount,@FreezeBalance)		
		-- 输出临时表
		SELECT AccountAmount,FreezeBalance FROM #tbBalances WHERE UserId=@UserId
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_User_Delete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_User_Delete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_User_Delete] 
	(
		@UserId INT,
		@Status INT OUTPUT
	)

AS
 
	DECLARE @intError_UserProfile INT
	DECLARE @intError_UserShippingAddresses INT
	DECLARE @intError_Users INT

	DECLARE @intError_NetUsersInRoles INT
	DECLARE @intError_NetProfile INT
	DECLARE @intError_NetUsers INT
	DECLARE @intError_NetMembership INT
	DECLARE @intError_MemberRanks INT
	DECLARE @intError_DeductRequest INT
	DECLARE @intError_BalanceDetails INT
	DECLARE @intError_BalanceDrawRequest INT
	DECLARE @intError_BalanceFreezeDetails INT

	DECLARE @intErrorCode INT

	-- 初始化信息
	SELECT @Status = 99, @intErrorCode = 0
	
	IF EXISTS(SELECT UserId FROM Hishop_UserProfile WHERE ParentUserId = @UserId)
		RETURN
		
	SET XACT_ABORT ON	
	BEGIN TRAN

	DECLARE @MembershipId uniqueidentifier
	
	SELECT @MembershipId = MembershipId FROM Hishop_Users WHERE UserId = @UserId
	-- 删除系统表中成员信息
	DELETE FROM Hishop_UserProfile WHERE UserId = @UserId
	SET @intError_UserProfile = @@ERROR
	
	DELETE FROM Hishop_UserShippingAddresses WHERE UserId = @UserId
	SET @intError_UserShippingAddresses = @@ERROR
	
	DELETE FROM Hishop_Users WHERE UserId = @UserId
	SET @intError_Users = @@ERROR
	
    -- 删除.net成员表中用户信息	
	DELETE FROM aspnet_UsersInRoles WHERE UserId = @MembershipId
	SET @intError_NetUsersInRoles = @@ERROR

	DELETE FROM aspnet_Profile WHERE UserId = @MembershipId
	SET @intError_NetProfile = @@ERROR

	DELETE FROM aspnet_Membership WHERE UserId = @MembershipId
	SET @intError_NetMembership = @@ERROR

	DELETE FROM aspnet_Users WHERE UserId = @MembershipId
	SET @intError_NetUsers = @@ERROR

    -- 删除该会员创建的等级
    delete from Hishop_UserRanks where creatoruserId=@UserId
	SET @intError_MemberRanks = @@ERROR

    -- 删除提成记录
    delete from Hishop_DeductRequest where userid=@UserId
	SET @intError_DeductRequest = @@ERROR
	
    -- 删除帐户明细
    delete from Hishop_BalanceDetails where userId=@UserId
	SET @intError_BalanceDetails = @@ERROR
	
    -- 删除提现记录
    delete from Hishop_BalanceDrawRequest where Applicant=@UserId
	SET @intError_BalanceDrawRequest = @@ERROR
	
    -- 删除冻结金额记录
    delete from Hishop_BalanceFreezeDetails where userId=@UserId
	SET @intError_BalanceFreezeDetails = @@ERROR

    SET @intErrorCode = @intError_UserProfile+@intError_UserShippingAddresses+@intError_Users
			+ @intError_NetUsersInRoles+@intError_NetProfile+@intError_NetUsers+@intError_NetMembership
			+@intError_MemberRanks+ @intError_DeductRequest+@intError_BalanceDetails+@intError_BalanceDrawRequest+@intError_BalanceFreezeDetails

	IF @intErrorCode = 0
	BEGIN		
		SET @Status = 0
		COMMIT TRAN
	END
	ELSE
		ROLLBACK TRAN	
	RETURN' 
END
GO
/****** Object:  StoredProcedure [dbo].[spb_BanlanceDetailsUserName_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[spb_BanlanceDetailsUserName_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spb_BanlanceDetailsUserName_Get]
	@UserName nvarchar(256), 
	@IsAnonymous bit
AS
	SELECT * FROM Hishop_BalanceDetails B WHERE B.TradeDate = 
	(SELECT MAX(TradeDate) FROM Hishop_BalanceDetails WHERE Payee = 
	(SELECT hi_UserId FROM vw_Users_FullUser P WHERE P.UserName =@UserName AND P.IsAnonymous = @IsAnonymous ))' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_co_UpdateRefundOrderStock]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_co_UpdateRefundOrderStock]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_co_UpdateRefundOrderStock]
(
	@OrderId Nvarchar(50) =null
)
as 
BEGIN
  --- 更新商品总库存
	   Update Hishop_Products 
	   Set  Stock = 
	   CASE  When ISNULL( Stock,0)=0  Then NULL
	   When (Stock + (SELECT SUM(oi.ShipmentQuantity) FROM Hishop_OrderItems oi
	   Where oi.ProductId =Hishop_Products.ProductId AND OrderId =@OrderId))<=0 Then 0 
       else  Stock + (SELECT SUM(oi.ShipmentQuantity) FROM Hishop_OrderItems oi
	  Where oi.ProductId =Hishop_Products.ProductId AND OrderId =@OrderId) 
	  END
	  WHere Hishop_Products.ProductId  IN (Select ProductId FROM Hishop_OrderItems Where   OrderId =@OrderId)
  --- 更新SKU库存
	   Update Hishop_SKUs 
	   Set  Stock = 
	   CASE  
	         WHEN ISNULL( Stock,0)=0  Then NULL
	         WHEN (Stock + (SELECT SUM(oi.ShipmentQuantity) FROM Hishop_OrderItems oi Where oi.SKU =Hishop_SKUs.SKU AND OrderId =@OrderId))<=0 Then 0 ELSE Stock + (SELECT SUM(oi.ShipmentQuantity) FROM Hishop_OrderItems oi  Where oi.SKU =Hishop_SKUs.SKU AND OrderId =@OrderId) 
	   END
	  WHERE Hishop_SKUs.SKU  IN (Select SKU FROM Hishop_OrderItems Where OrderId =@OrderId)
  -- 更新礼品库存
	  Update Hishop_Gifts
	  Set Stock =
	  CASE When ISNULL(Stock,0)= 0 Then NULL
      WHEN Stock +1 <=0 Then 0
	  ELSE Stock +1
	  END 
	  Where GiftId IN (Select GiftId FROM Hishop_OrderGifts Where OrderId= @OrderId)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_co_UpdatePayOrderStock]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_co_UpdatePayOrderStock]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_co_UpdatePayOrderStock]
(
	@OrderId Nvarchar(50) =null
)
as 
BEGIN
  --- 更新商品总库存
	   Update Hishop_Products 
	   Set  Stock = 
	   CASE  When ISNULL( Stock,0)=0  Then NULL
	   When (Stock - (SELECT SUM(oi.ShipmentQuantity) FROM Hishop_OrderItems oi
	   Where oi.ProductId =Hishop_Products.ProductId AND OrderId =@OrderId))<=0 Then 0 
       else  Stock - (SELECT SUM(oi.ShipmentQuantity) FROM Hishop_OrderItems oi
	  Where oi.ProductId =Hishop_Products.ProductId AND OrderId =@OrderId) 
	  END
	  WHere Hishop_Products.ProductId  IN (Select ProductId FROM Hishop_OrderItems Where   OrderId =@OrderId)
  --- 更新SKU库存
	   Update Hishop_SKUs 
	   Set  Stock = 
	   CASE  
	         WHEN ISNULL( Stock,0)=0  Then NULL
	         WHEN (Stock - (SELECT SUM(oi.ShipmentQuantity) FROM Hishop_OrderItems oi Where oi.SKU =Hishop_SKUs.SKU AND OrderId =@OrderId))<=0 Then 0 ELSE Stock - (SELECT SUM(oi.ShipmentQuantity) FROM Hishop_OrderItems oi  Where oi.SKU =Hishop_SKUs.SKU AND OrderId =@OrderId) 
	   END
	  WHERE Hishop_SKUs.SKU  IN (Select SKU FROM Hishop_OrderItems Where OrderId =@OrderId)
  -- 更新礼品库存
	  Update Hishop_Gifts
	  Set Stock =
	  CASE When ISNULL(Stock,0)= 0 Then NULL
      WHEN Stock -1 <=0 Then 0
	  ELSE Stock -1
	  END 
	  Where GiftId IN (Select GiftId FROM Hishop_OrderGifts Where OrderId= @OrderId)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_ProductExpandCategory_Add]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_ProductExpandCategory_Add]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_ProductExpandCategory_Add] 
	(
		@ProductId INT,
		@CategoryId INT
	)

AS
	-- 检查商品是否已经扩展了指定的分类
	IF EXISTS(SELECT * FROM Hishop_ProductExtendCategories WHERE ProductId = @ProductId AND CategoryId = @CategoryId)
		RETURN
		
	-- 检查商品是否存在
	IF NOT EXISTS(SELECT ProductName FROM Hishop_Products WHERE ProductId = @ProductId)
		RETURN
		
	INSERT INTO 
		Hishop_ProductExtendCategories (ProductId, CategoryId) 
	VALUES 
		(@ProductId, @CategoryId)' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Give_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Give_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Give_Get]
 (
    @DateTime DateTime
)
as
BEGIN
 SELECT ps.*, pg.BuyQuantity,pg.GiveQuantity
 From Hishop_PromoteSales ps INNER JOIN Hishop_PromoteSales_Give pg 
                   ON ps.ActivityId = pg.ActivityId  Where ps.ClosingTime >@DateTime AND ps.StartTime<@DateTime
                    Order by BuyQuantity DESC
  SELECT * FROM Hishop_PromoteSales_Products
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_Supplier_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_Supplier_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_Supplier_CreateUpdateDelete] 
	(
		@SupplierId INT = NULL,
		@Name NVARCHAR(50) = NULL,
		@TelPhone NVARCHAR(50) = NULL,
		@CellPhone NVARCHAR(50) = NULL,
		@Address NVARCHAR(500) = NULL,
		@Remark NVARCHAR(1000) = NULL,
		@Contact NVARCHAR(50) = NULL,
		@Action INT
	)
AS
	
	IF @Action = 2 -- 删除
	BEGIN	

		DELETE FROM
			Hishop_Suppliers
		WHERE
			SupplierId = @SupplierId
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN
		
		INSERT INTO Hishop_Suppliers([Name], TelPhone, CellPhone, Address, Remark, Contact)
		VALUES (@Name, @TelPhone, @CellPhone, @Address, @Remark, @Contact)
		
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
		UPDATE 
			Hishop_Suppliers 
		SET 
			[Name] = @Name,
			TelPhone = @TelPhone,
			CellPhone = @CellPhone,
			Address = @Address,
			Remark = @Remark,
			Contact = @Contact
		WHERE SupplierId = @SupplierId
			
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Supplier_NameExists]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Supplier_NameExists]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Supplier_NameExists] 
	(
		@SupplierId INT	 = NULL,
		@Name NVARCHAR(200),
		@Exists BIT = 0 OUTPUT
	)
AS
	SET @Exists = 0
	
	IF @SupplierId IS NULL
	BEGIN
		IF EXISTS(SELECT SupplierId FROM Hishop_Suppliers WHERE LOWER([Name]) = LOWER(@Name))
			SELECT @Exists = 1
	END
	
	ELSE
	BEGIN
		IF EXISTS(SELECT SupplierId FROM Hishop_Suppliers WHERE LOWER([Name]) = LOWER(@Name) AND SupplierId != @SupplierId)
			SELECT @Exists = 1
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_PromoteQuantityDiscount_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_PromoteQuantityDiscount_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_PromoteQuantityDiscount_Get]
	(
 @DateTime DateTime
)
as
BEGIN
SELECT ps.*,pq.Quantity,pq.DiscountValue From Hishop_PromoteSales ps INNER JOIN 
Hishop_PromoteSales_QuantityDiscount pq  ON ps.ActivityId = pq.ActivityId WHERE ps.ClosingTime >@DateTime AND ps.StartTime<@DateTime
Order By Quantity DESC
SELECT * FROM Hishop_PromoteSales_Products
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_BannedAddresses_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_BannedAddresses_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_BannedAddresses_Get]

AS
	SELECT
		  NetworkAddress
		, BannedDate
	FROM Hishop_BannedAddresses' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_BannedAddress_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_BannedAddress_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_BannedAddress_CreateUpdateDelete]
	  @NetworkAddress	NVARCHAR(50) 
	, @BannedDate		DATETIME
	, @ActionType		INT
AS
	DECLARE @ID INT
	DECLARE @ERROR INT
	DECLARE @ROWCOUNT INT
	
	-- CREATE
	IF @ActionType = 0 
	BEGIN
		IF EXISTS( SELECT * FROM Hishop_BannedAddresses where NetworkAddress = @NetworkAddress )
			exec sp_cg_BannedAddress_CreateUpdateDelete @NetworkAddress, @BannedDate, 1 
		else
		BEGIN
		
			INSERT INTO Hishop_BannedAddresses VALUES(@NetworkAddress, @BannedDate )

			SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR( ''An error occurred while trying to create a new Hishop_BannedAddresses record.'', 16, 1 )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0
			END
		END
	END
	ELSE IF( @ActionType = 1 )
	BEGIN
		-- UPDATE
		IF NOT EXISTS( SELECT * FROM Hishop_BannedAddresses WHERE NetworkAddress = @NetworkAddress )
			exec sp_cg_BannedAddress_CreateUpdateDelete @NetworkAddress, @BannedDate, 0 
		ELSE
		BEGIN
			UPDATE Hishop_BannedAddresses SET
				NetworkAddress = @NetworkAddress,
				BannedDate = @BannedDate
			WHERE
				NetworkAddress = @NetworkAddress
				
			SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR(''Could not update the Hishop_BannedAddresses record for NetworkAddress %d'', 16, 1, @NetworkAddress )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0				
			END
		END
	END
	ELSE IF( @ActionType = 2 )
	BEGIN
		-- DELETE
		DELETE Hishop_BannedAddresses
		WHERE NetworkAddress = @NetworkAddress
			
		SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
		IF( @ROWCOUNT = 1 )
			RETURN 0
		ELSE
			RETURN 1
		
	END
	ELSE
	BEGIN
		RAISERROR( ''The ActionType value should be between 0 and 2. The value of %d was not within this range'', 16, 1, @ActionType )
		RETURN 1
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spb_PromoteGifts_CreateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[spb_PromoteGifts_CreateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spb_PromoteGifts_CreateDelete]
	@ActivityId int, 
	@GiftId int,
	@GiftPrice money=0,
	@Action INT,
    @Status INT OUTPUT
AS
	-- 初始化信息
	SELECT @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN
		DELETE FROM Hishop_PromoteSales_Gifts WHERE ActivityId=@ActivityId AND GiftId=@GiftId
		IF @@ROWCOUNT = 1
		    SET @Status = 0
		RETURN
	END
	
	IF @Action = 0 -- 创建
    BEGIN
		INSERT Hishop_PromoteSales_Gifts(ActivityId,GiftId,GiftPrice)VALUES(@ActivityId,@GiftId,@GiftPrice)
		IF @@ROWCOUNT = 1
			SET @Status = 0
		RETURN
    END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ca_Gift_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ca_Gift_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ca_Gift_CreateUpdateDelete] 
	(
		@GiftId INT = NULL OUTPUT,
		@Name NVARCHAR(100) = NULL,
		@ShortDescription NVARCHAR(2000) = NULL,
		@Unit NVARCHAR(10) = NULL,
		@LongDescription NTEXT = NULL,
		@Title NVARCHAR(100) = NULL,
		@Meta_Description NVARCHAR(1000) = NULL,
		@Meta_Keywords NVARCHAR(1000) = NULL,
		@ThumbnailsUrl NVARCHAR(255) = NULL,
		@InFocusImageUrl NVARCHAR(255) = NULL,
		@CostPrice MONEY = NULL,
		@MarketPrice MONEY = NULL,
		@SalePrice MONEY = NULL,
		@Weight INT = NULL,
		@Enabled BIT = NULL,
        @Stock INT =NULL,
		@Action INT,
		@Status INT OUTPUT
	)
AS
	SET @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN
	
		DELETE FROM Hishop_Gifts WHERE GiftId = @GiftId
		IF @@ROWCOUNT = 1
			BEGIN
				DELETE FROM Hishop_PromoteSales_Gifts WHERE Hishop_PromoteSales_Gifts.GiftId=@GiftId
				SET @Status = 0
			END
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN
		
		INSERT INTO 
			Hishop_Gifts
			([Name], ShortDescription, Unit, LongDescription, Title, 
			Meta_Description, Meta_Keywords, ThumbnailsUrl, InFocusImageUrl, CostPrice, 
			MarketPrice, Enabled, SalePrice, Stock, Weight)
		VALUES 
			(@Name, @ShortDescription, @Unit, @LongDescription, @Title, 
			@Meta_Description, @Meta_Keywords, @ThumbnailsUrl, @InFocusImageUrl, @CostPrice, 
			@MarketPrice, @Enabled, @SalePrice, @Stock, @Weight)
			
		SELECT @GiftId = @@IDENTITY
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
		UPDATE 
			Hishop_Gifts 
		SET 
			[Name] = @Name,
			ShortDescription = @ShortDescription,
			Unit = @Unit,
			LongDescription = @LongDescription,
			Title = @Title,
			Meta_Description = @Meta_Description,
			Meta_Keywords = @Meta_Keywords,
			ThumbnailsUrl = @ThumbnailsUrl,
			InFocusImageUrl = @InFocusImageUrl,
			CostPrice = @CostPrice,
			MarketPrice = @MarketPrice,
			Enabled = @Enabled,
			SalePrice = @SalePrice,
			Weight = @Weight,
            Stock =@Stock
		WHERE GiftId = @GiftId
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Present_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Present_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Present_Get]
(
	@DateTime DateTime
)
as
BEGIN
	SELECT ps.*,pp.Amount,pp.PresenteCount From Hishop_PromoteSales ps INNER JOIN Hishop_PromoteSales_Present pp 
	 ON ps.ActivityId = pp.ActivityId Where ps.ClosingTime >@DateTime AND ps.StartTime<@DateTime Order By Amount Desc
	 SELECT hpg.*,hg.Name,hg.Weight,hg.CostPrice FROM Hishop_PromoteSales_Gifts hpg INNER JOIN Hishop_Gifts hg  
	 ON hpg.GiftId = hg.GiftId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ca_Coupon_Update]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ca_Coupon_Update]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ca_Coupon_Update] 
	(
		@CouponId INT,
		@Name NVARCHAR(100),
		@EnabledTimes INT,
		@ClosingTime DATETIME,
		@Description NTEXT = NULL,
		@Amount MONEY=NULL,
		@DiscountValue MONEY,
		@Status INT OUTPUT
	)

AS
	SET @Status = 99
	
	UPDATE Hishop_Coupons 
		SET [Name]=@Name, EnabledTimes=@EnabledTimes, ClosingTime=@ClosingTime,
		    Description=@Description, Amount=@Amount, DiscountValue=@DiscountValue
	WHERE
		CouponId=@CouponId
		
	IF @@ROWCOUNT = 1
		SET @Status = 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ca_Coupon_Create]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ca_Coupon_Create]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ca_Coupon_Create] 
	(
		@Name NVARCHAR(100),
		@EnabledTimes INT,
		@ClosingTime DATETIME,
		@Description NTEXT = NULL,
		@Amount MONEY,
		@DiscountValue MONEY,
		@Status INT OUTPUT
	)

AS
	SET @Status = 99
	
	INSERT INTO 
		Hishop_Coupons ([Name], EnabledTimes,  ClosingTime, Description, Amount, DiscountValue)
	VALUES
		(@Name, @EnabledTimes, @ClosingTime, @Description, @Amount, @DiscountValue)
		
	IF @@ROWCOUNT = 1
		SET @Status = 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ca_Coupon_Delete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ca_Coupon_Delete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ca_Coupon_Delete]
	(
		@CouponId INT
	)
AS
	/*
	1、删除已申明的优惠券列表
	2、删除已派送的优惠券列表
	3、删除优惠券
	*/
	SET XACT_ABORT ON
	
	DECLARE @intErrorCode INT
	SET @intErrorCode = 0
	
	BEGIN TRAN
	
	DELETE FROM Hishop_ClaimedCoupons WHERE ClaimCode IN (SELECT ClaimCode FROM Hishop_CouponItems WHERE CouponId = @CouponId)
	SET @intErrorCode = @@ERROR
	
	IF @intErrorCode = 0
	BEGIN
		DELETE FROM Hishop_CouponItems WHERE CouponId = @CouponId
		SET @intErrorCode = @@ERROR
	END
	
	IF @intErrorCode = 0
	BEGIN
		DELETE FROM Hishop_Coupons WHERE CouponId = @CouponId
		IF @@ROWCOUNT = 0
			SET @intErrorCode = -1
		ELSE
			SET @intErrorCode = @@ERROR
	END
	
	IF @intErrorCode = 0
		COMMIT TRAN
	ELSE
		ROLLBACK TRAN
		
	SELECT @intErrorCode' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Coupons_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Coupons_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Coupons_Get]
(
   @ClaimCode Nvarchar(50) =null,
   @DateTime DateTime
)
as 
	BEGIN
		SELECT c.* FROM Hishop_Coupons c 
		INNER  JOIN Hishop_CouponItems ci
		ON ci.CouponId = c.CouponId
		Where ci.ClaimCode =@ClaimCode AND @DateTime <c.ClosingTime
         AND c.EnabledTimes >
			(select 
				(SELECT COUNT(claimcode) FROM Hishop_ClaimedCoupons 
					WHERE claimcode =@ClaimCode) AS EnabledTimes)
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_UsersInRoles_GetRolesForUser]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_UsersInRoles_GetRolesForUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_UsersInRoles_GetRolesForUser]
    @ApplicationName  nvarchar(256),
    @UserName         nvarchar(256)
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN(1)
    DECLARE @UserId uniqueidentifier
    SELECT  @UserId = NULL

    SELECT  @UserId = UserId
    FROM    dbo.aspnet_Users
    WHERE   LoweredUserName = LOWER(@UserName) AND ApplicationId = @ApplicationId

    IF (@UserId IS NULL)
        RETURN(1)

    SELECT r.RoleName
    FROM   dbo.aspnet_Roles r, dbo.aspnet_UsersInRoles ur
    WHERE  r.RoleId = ur.RoleId AND r.ApplicationId = @ApplicationId AND ur.UserId = @UserId
    ORDER BY r.RoleName
    RETURN (0)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_UsersInRoles_IsUserInRole]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_UsersInRoles_IsUserInRole]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_UsersInRoles_IsUserInRole]
    @ApplicationName  nvarchar(256),
    @UserName         nvarchar(256),
    @RoleName         nvarchar(256)
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN(2)
    DECLARE @UserId uniqueidentifier
    SELECT  @UserId = NULL
    DECLARE @RoleId uniqueidentifier
    SELECT  @RoleId = NULL

    SELECT  @UserId = UserId
    FROM    dbo.aspnet_Users
    WHERE   LoweredUserName = LOWER(@UserName) AND ApplicationId = @ApplicationId

    IF (@UserId IS NULL)
        RETURN(2)

    SELECT  @RoleId = RoleId
    FROM    dbo.aspnet_Roles
    WHERE   LoweredRoleName = LOWER(@RoleName) AND ApplicationId = @ApplicationId

    IF (@RoleId IS NULL)
        RETURN(3)

    IF (EXISTS( SELECT * FROM dbo.aspnet_UsersInRoles WHERE  UserId = @UserId AND RoleId = @RoleId))
        RETURN(1)
    ELSE
        RETURN(0)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_UsersInRoles_FindUsersInRole]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_UsersInRoles_FindUsersInRole]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_UsersInRoles_FindUsersInRole]
    @ApplicationName  nvarchar(256),
    @RoleName         nvarchar(256),
    @UserNameToMatch  nvarchar(256)
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN(1)
     DECLARE @RoleId uniqueidentifier
     SELECT  @RoleId = NULL

     SELECT  @RoleId = RoleId
     FROM    dbo.aspnet_Roles
     WHERE   LOWER(@RoleName) = LoweredRoleName AND ApplicationId = @ApplicationId

     IF (@RoleId IS NULL)
         RETURN(1)

    SELECT u.UserName
    FROM   dbo.aspnet_Users u, dbo.aspnet_UsersInRoles ur
    WHERE  u.UserId = ur.UserId AND @RoleId = ur.RoleId AND u.ApplicationId = @ApplicationId AND LoweredUserName LIKE LOWER(@UserNameToMatch)
    ORDER BY u.UserName
    RETURN(0)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_UserPrivileges_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_UserPrivileges_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_UserPrivileges_Get]
    @ApplicationName  nvarchar(256),
    @UserName         nvarchar(256)
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    DECLARE @UserId uniqueidentifier

    SELECT  @UserId = NULL

    SELECT  @UserId = UserId
    FROM    dbo.aspnet_Users
    WHERE   LoweredUserName = LOWER(@UserName) AND ApplicationId = @ApplicationId

    SELECT DISTINCT pr.ResourceId, pr.OperationId
    FROM   
		dbo.aspnet_Roles r INNER JOIN dbo.aspnet_UsersInRoles ur ON r.RoleId = ur.RoleId
		INNER JOIN dbo.Hishop_PrivilegeInRoles pr ON pr.RoleId = r.RoleId
    WHERE r.ApplicationId = @ApplicationId AND ur.UserId = @UserId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_UsersInRoles_RemoveUsersFromRoles]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_UsersInRoles_RemoveUsersFromRoles]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_UsersInRoles_RemoveUsersFromRoles]
	@ApplicationName  nvarchar(256),
	@UserNames		  nvarchar(4000),
	@RoleNames		  nvarchar(4000)
AS
BEGIN
	DECLARE @AppId uniqueidentifier
	SELECT  @AppId = NULL
	SELECT  @AppId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
	IF (@AppId IS NULL)
		RETURN(2)


	DECLARE @TranStarted   bit
	SET @TranStarted = 0

	IF( @@TRANCOUNT = 0 )
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @tbNames  table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @tbRoles  table(RoleId uniqueidentifier NOT NULL PRIMARY KEY)
	DECLARE @tbUsers  table(UserId uniqueidentifier NOT NULL PRIMARY KEY)
	DECLARE @Num	  int
	DECLARE @Pos	  int
	DECLARE @NextPos  int
	DECLARE @Name	  nvarchar(256)
	DECLARE @CountAll int
	DECLARE @CountU	  int
	DECLARE @CountR	  int


	SET @Num = 0
	SET @Pos = 1
	WHILE(@Pos <= LEN(@RoleNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N'','', @RoleNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@RoleNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@RoleNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos+1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbRoles
	  SELECT RoleId
	  FROM   dbo.aspnet_Roles ar, @tbNames t
	  WHERE  LOWER(t.Name) = ar.LoweredRoleName AND ar.ApplicationId = @AppId
	SELECT @CountR = @@ROWCOUNT

	IF (@CountR <> @Num)
	BEGIN
		SELECT TOP 1 N'''', Name
		FROM   @tbNames
		WHERE  LOWER(Name) NOT IN (SELECT ar.LoweredRoleName FROM dbo.aspnet_Roles ar,  @tbRoles r WHERE r.RoleId = ar.RoleId)
		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(2)
	END


	DELETE FROM @tbNames WHERE 1=1
	SET @Num = 0
	SET @Pos = 1


	WHILE(@Pos <= LEN(@UserNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N'','', @UserNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@UserNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@UserNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos+1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbUsers
	  SELECT UserId
	  FROM   dbo.aspnet_Users ar, @tbNames t
	  WHERE  LOWER(t.Name) = ar.LoweredUserName AND ar.ApplicationId = @AppId

	SELECT @CountU = @@ROWCOUNT
	IF (@CountU <> @Num)
	BEGIN
		SELECT TOP 1 Name, N''''
		FROM   @tbNames
		WHERE  LOWER(Name) NOT IN (SELECT au.LoweredUserName FROM dbo.aspnet_Users au,  @tbUsers u WHERE u.UserId = au.UserId)

		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(1)
	END

	SELECT  @CountAll = COUNT(*)
	FROM	dbo.aspnet_UsersInRoles ur, @tbUsers u, @tbRoles r
	WHERE   ur.UserId = u.UserId AND ur.RoleId = r.RoleId

	IF (@CountAll <> @CountU * @CountR)
	BEGIN
		SELECT TOP 1 UserName, RoleName
		FROM		 @tbUsers tu, @tbRoles tr, dbo.aspnet_Users u, dbo.aspnet_Roles r
		WHERE		 u.UserId = tu.UserId AND r.RoleId = tr.RoleId AND
					 tu.UserId NOT IN (SELECT ur.UserId FROM dbo.aspnet_UsersInRoles ur WHERE ur.RoleId = tr.RoleId) AND
					 tr.RoleId NOT IN (SELECT ur.RoleId FROM dbo.aspnet_UsersInRoles ur WHERE ur.UserId = tu.UserId)
		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(3)
	END

	DELETE FROM dbo.aspnet_UsersInRoles
	WHERE UserId IN (SELECT UserId FROM @tbUsers)
	  AND RoleId IN (SELECT RoleId FROM @tbRoles)
	IF( @TranStarted = 1 )
		COMMIT TRANSACTION
	RETURN(0)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_UsersInRoles_AddUsersToRoles]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_UsersInRoles_AddUsersToRoles]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_UsersInRoles_AddUsersToRoles]
	@ApplicationName  nvarchar(256),
	@UserNames		  nvarchar(4000),
	@RoleNames		  nvarchar(4000),
	@CurrentTimeUtc   datetime
AS
BEGIN
	DECLARE @AppId uniqueidentifier
	SELECT  @AppId = NULL
	SELECT  @AppId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
	IF (@AppId IS NULL)
		RETURN(2)
	DECLARE @TranStarted   bit
	SET @TranStarted = 0

	IF( @@TRANCOUNT = 0 )
	BEGIN
		BEGIN TRANSACTION
		SET @TranStarted = 1
	END

	DECLARE @tbNames	table(Name nvarchar(256) NOT NULL PRIMARY KEY)
	DECLARE @tbRoles	table(RoleId uniqueidentifier NOT NULL PRIMARY KEY)
	DECLARE @tbUsers	table(UserId uniqueidentifier NOT NULL PRIMARY KEY)
	DECLARE @Num		int
	DECLARE @Pos		int
	DECLARE @NextPos	int
	DECLARE @Name		nvarchar(256)

	SET @Num = 0
	SET @Pos = 1
	WHILE(@Pos <= LEN(@RoleNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N'','', @RoleNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@RoleNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@RoleNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos+1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbRoles
	  SELECT RoleId
	  FROM   dbo.aspnet_Roles ar, @tbNames t
	  WHERE  LOWER(t.Name) = ar.LoweredRoleName AND ar.ApplicationId = @AppId

	IF (@@ROWCOUNT <> @Num)
	BEGIN
		SELECT TOP 1 Name
		FROM   @tbNames
		WHERE  LOWER(Name) NOT IN (SELECT ar.LoweredRoleName FROM dbo.aspnet_Roles ar,  @tbRoles r WHERE r.RoleId = ar.RoleId)
		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(2)
	END

	DELETE FROM @tbNames WHERE 1=1
	SET @Num = 0
	SET @Pos = 1

	WHILE(@Pos <= LEN(@UserNames))
	BEGIN
		SELECT @NextPos = CHARINDEX(N'','', @UserNames,  @Pos)
		IF (@NextPos = 0 OR @NextPos IS NULL)
			SELECT @NextPos = LEN(@UserNames) + 1
		SELECT @Name = RTRIM(LTRIM(SUBSTRING(@UserNames, @Pos, @NextPos - @Pos)))
		SELECT @Pos = @NextPos+1

		INSERT INTO @tbNames VALUES (@Name)
		SET @Num = @Num + 1
	END

	INSERT INTO @tbUsers
	  SELECT UserId
	  FROM   dbo.aspnet_Users ar, @tbNames t
	  WHERE  LOWER(t.Name) = ar.LoweredUserName AND ar.ApplicationId = @AppId

	IF (@@ROWCOUNT <> @Num)
	BEGIN
		DELETE FROM @tbNames
		WHERE LOWER(Name) IN (SELECT LoweredUserName FROM dbo.aspnet_Users au,  @tbUsers u WHERE au.UserId = u.UserId)

		INSERT dbo.aspnet_Users (ApplicationId, UserId, UserName, LoweredUserName, IsAnonymous, LastActivityDate)
		  SELECT @AppId, NEWID(), Name, LOWER(Name), 0, @CurrentTimeUtc
		  FROM   @tbNames

		INSERT INTO @tbUsers
		  SELECT  UserId
		  FROM	dbo.aspnet_Users au, @tbNames t
		  WHERE   LOWER(t.Name) = au.LoweredUserName AND au.ApplicationId = @AppId
	END

	IF (EXISTS (SELECT * FROM dbo.aspnet_UsersInRoles ur, @tbUsers tu, @tbRoles tr WHERE tu.UserId = ur.UserId AND tr.RoleId = ur.RoleId))
	BEGIN
		SELECT TOP 1 UserName, RoleName
		FROM		 dbo.aspnet_UsersInRoles ur, @tbUsers tu, @tbRoles tr, aspnet_Users u, aspnet_Roles r
		WHERE		u.UserId = tu.UserId AND r.RoleId = tr.RoleId AND tu.UserId = ur.UserId AND tr.RoleId = ur.RoleId

		IF( @TranStarted = 1 )
			ROLLBACK TRANSACTION
		RETURN(3)
	END

	INSERT INTO dbo.aspnet_UsersInRoles (UserId, RoleId)
	SELECT UserId, RoleId
	FROM @tbUsers, @tbRoles

	IF( @TranStarted = 1 )
		COMMIT TRANSACTION
	RETURN(0)
END' 
END
GO
/****** Object:  View [dbo].[vw_aspnet_UsersInRoles]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[vw_aspnet_UsersInRoles]') AND OBJECTPROPERTY(id, N'IsView') = 1)
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vw_aspnet_UsersInRoles]
  AS SELECT [dbo].[aspnet_UsersInRoles].[UserId], [dbo].[aspnet_UsersInRoles].[RoleId]
  FROM [dbo].[aspnet_UsersInRoles]'
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Users_DeleteUser]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Users_DeleteUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Users_DeleteUser]
    @ApplicationName  nvarchar(256),
    @UserName         nvarchar(256),
    @TablesToDeleteFrom int,
    @NumTablesDeletedFrom int OUTPUT
AS
BEGIN
    DECLARE @UserId               uniqueidentifier
    SELECT  @UserId               = NULL
    SELECT  @NumTablesDeletedFrom = 0

    DECLARE @TranStarted   bit
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
	    BEGIN TRANSACTION
	    SET @TranStarted = 1
    END
    ELSE
	SET @TranStarted = 0

    DECLARE @ErrorCode   int
    DECLARE @RowCount    int

    SET @ErrorCode = 0
    SET @RowCount  = 0

    SELECT  @UserId = u.UserId
    FROM    dbo.aspnet_Users u, dbo.aspnet_Applications a
    WHERE   u.LoweredUserName       = LOWER(@UserName)
        AND u.ApplicationId         = a.ApplicationId
        AND LOWER(@ApplicationName) = a.LoweredApplicationName

    IF (@UserId IS NULL)
    BEGIN
        GOTO Cleanup
    END

    -- Delete from Membership table if (@TablesToDeleteFrom & 1) is set
    IF ((@TablesToDeleteFrom & 1) <> 0 AND
        (EXISTS (SELECT name FROM sysobjects WHERE (name = N''vw_aspnet_MembershipUsers'') AND (type = ''V''))))
    BEGIN
        DELETE FROM dbo.aspnet_Membership WHERE @UserId = UserId

        SELECT @ErrorCode = @@ERROR,
               @RowCount = @@ROWCOUNT

        IF( @ErrorCode <> 0 )
            GOTO Cleanup

        IF (@RowCount <> 0)
            SELECT  @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
    END

    -- Delete from aspnet_UsersInRoles table if (@TablesToDeleteFrom & 2) is set
    IF ((@TablesToDeleteFrom & 2) <> 0  AND
        (EXISTS (SELECT name FROM sysobjects WHERE (name = N''vw_aspnet_UsersInRoles'') AND (type = ''V''))) )
    BEGIN
        DELETE FROM dbo.aspnet_UsersInRoles WHERE @UserId = UserId

        SELECT @ErrorCode = @@ERROR,
                @RowCount = @@ROWCOUNT

        IF( @ErrorCode <> 0 )
            GOTO Cleanup

        IF (@RowCount <> 0)
            SELECT  @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
    END

    -- Delete from aspnet_Profile table if (@TablesToDeleteFrom & 4) is set
    IF ((@TablesToDeleteFrom & 4) <> 0  AND
        (EXISTS (SELECT name FROM sysobjects WHERE (name = N''vw_aspnet_Profiles'') AND (type = ''V''))) )
    BEGIN
        DELETE FROM dbo.aspnet_Profile WHERE @UserId = UserId

        SELECT @ErrorCode = @@ERROR,
                @RowCount = @@ROWCOUNT

        IF( @ErrorCode <> 0 )
            GOTO Cleanup

        IF (@RowCount <> 0)
            SELECT  @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
    END

    -- Delete from aspnet_Users table if (@TablesToDeleteFrom & 1,2,4 & 8) are all set
    IF ((@TablesToDeleteFrom & 1) <> 0 AND
        (@TablesToDeleteFrom & 2) <> 0 AND
        (@TablesToDeleteFrom & 4) <> 0 AND
        (@TablesToDeleteFrom & 8) <> 0 AND
        (EXISTS (SELECT UserId FROM dbo.aspnet_Users WHERE @UserId = UserId)))
    BEGIN
        DELETE FROM dbo.aspnet_Users WHERE @UserId = UserId

        SELECT @ErrorCode = @@ERROR,
                @RowCount = @@ROWCOUNT

        IF( @ErrorCode <> 0 )
            GOTO Cleanup

        IF (@RowCount <> 0)
            SELECT  @NumTablesDeletedFrom = @NumTablesDeletedFrom + 1
    END

    IF( @TranStarted = 1 )
    BEGIN
	    SET @TranStarted = 0
	    COMMIT TRANSACTION
    END

    RETURN 0

Cleanup:
    SET @NumTablesDeletedFrom = 0

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
	    ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Roles_DeleteRole]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Roles_DeleteRole]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Roles_DeleteRole]
    @ApplicationName            nvarchar(256),
    @RoleName                   nvarchar(256),
    @DeleteOnlyIfRoleIsEmpty    bit
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN(1)

    DECLARE @ErrorCode     int
    SET @ErrorCode = 0

    DECLARE @TranStarted   bit
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
        SET @TranStarted = 0

    DECLARE @RoleId   uniqueidentifier
    SELECT  @RoleId = NULL
    SELECT  @RoleId = RoleId FROM dbo.aspnet_Roles WHERE LoweredRoleName = LOWER(@RoleName) AND ApplicationId = @ApplicationId

    IF (@RoleId IS NULL)
    BEGIN
        SELECT @ErrorCode = 1
        GOTO Cleanup
    END
    IF (@DeleteOnlyIfRoleIsEmpty <> 0)
    BEGIN
        IF (EXISTS (SELECT RoleId FROM dbo.aspnet_UsersInRoles  WHERE @RoleId = RoleId))
        BEGIN
            SELECT @ErrorCode = 2
            GOTO Cleanup
        END
    END


    DELETE FROM dbo.aspnet_UsersInRoles  WHERE @RoleId = RoleId

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DELETE FROM dbo.aspnet_Roles WHERE @RoleId = RoleId  AND ApplicationId = @ApplicationId

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Roles_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Roles_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[sp_Roles_Get]
(
	@UserId int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

Declare @ApplicationName nvarchar(256)
Select @ApplicationName = ApplicationName from Hishop_SiteSettings

DECLARE @ApplicationId UNIQUEIDENTIFIER
SELECT  @ApplicationId = NULL
SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName


	IF (@UserId = 0)
		SELECT
			RoleId, RoleName as [Name], Description
		FROM
			aspnet_Roles where ApplicationId = @ApplicationId
	ELSE
		SELECT DISTINCT
			R.RoleId, RoleName as [Name], Description
		FROM 
			aspnet_UsersInRoles U,
			aspnet_Roles R,
			Hishop_UserProfile P
		WHERE
			U.RoleId = R.RoleId AND
			P.UserId = @UserId AND
			P.MembershipId = U.UserId and R.ApplicationId = @ApplicationId
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_UsersInRoles_GetUsersInRoles]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_UsersInRoles_GetUsersInRoles]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_UsersInRoles_GetUsersInRoles]
    @ApplicationName  nvarchar(256),
    @RoleName         nvarchar(256)
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN(1)
     DECLARE @RoleId uniqueidentifier
     SELECT  @RoleId = NULL

     SELECT  @RoleId = RoleId
     FROM    dbo.aspnet_Roles
     WHERE   LOWER(@RoleName) = LoweredRoleName AND ApplicationId = @ApplicationId

     IF (@RoleId IS NULL)
         RETURN(1)

    SELECT u.UserName
    FROM   dbo.aspnet_Users u, dbo.aspnet_UsersInRoles ur
    WHERE  u.UserId = ur.UserId AND @RoleId = ur.RoleId AND u.ApplicationId = @ApplicationId
    ORDER BY u.UserName
    RETURN(0)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Roles_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Roles_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Roles_CreateUpdateDelete]
(
	@RoleId	uniqueidentifier out,
	@DeleteRole	bit = 0,
	@Name		nvarchar(256) = '''',
	@Description	nvarchar(512) = ''''

)
AS
DECLARE	@ApplicationName nvarchar(256)
Select @ApplicationName = ApplicationName from Hishop_SiteSettings

DECLARE @ApplicationId UNIQUEIDENTIFIER
SELECT  @ApplicationId = NULL
SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName

if(@ApplicationId IS NULL)
RETURN
 
IF @RoleId is not null
Begin

	--validate application/role context
	IF NOT EXISTS(Select RoleId FROM aspnet_Roles where RoleId = @RoleId  and ApplicationId = @ApplicationId)
	RETURN


	-- Are we deleting the role?
	IF @DeleteRole = 1
	BEGIN
	
		-- 删除用户权限
		DELETE FROM
			Hishop_PrivilegeInRoles
		WHERE 
			RoleId = @RoleId
	
		-- delete all users in the role
		DELETE 
			aspnet_UsersInRoles
		WHERE 
			RoleId = @RoleId	
	
		-- finally we can delete the actual role
		DELETE 
			aspnet_Roles
		WHERE 
			RoleId = @RoleId
	
	END
	ELSE
	BEGIN
		-- Update the role
				-- 修改角色信息
		IF EXISTS(SELECT * FROM aspnet_Roles WHERE LoweredRoleName = LOWER(@Name) AND RoleId != @RoleId)
			RETURN
			
		UPDATE 
			aspnet_Roles
		SET
			RoleName = @Name,
			LoweredRoleName = Lower(@Name),
			Description = @Description
		WHERE 
			RoleId = @RoleId
	END
END
ELSE
BEGIN

	-- Create a new Role
	INSERT INTO 
		aspnet_Roles (
			RoleName, 
			LoweredRoleName,
			Description
			)
		VALUES (
			@Name,
			Lower(@Name),
			@Description
			)
	
	Select @RoleId = RoleId FROM aspnet_Roles where LoweredRoleName = Lower(@Name) and ApplicationId = @ApplicationId

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_BrandCategory_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_BrandCategory_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_BrandCategory_CreateUpdateDelete]
	(
		@BrandId INT = NULL,
		@BrandName NVARCHAR(50) = NULL,
		@Logo NVARCHAR(255) = NULL,
		@CompanyUrl NVARCHAR(255) = NULL,
		@Description NVARCHAR(4000) = NULL,
		@Action INT,
		@Status INT OUTPUT
	)
AS
	SET @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN -- 同时修改商品品牌
	
		SET XACT_ABORT ON
		DECLARE @intErrorCode INT
		
		BEGIN TRAN
		
		UPDATE Hishop_Products SET BrandId = 0 WHERE BrandId = @BrandId
		SET @intErrorCode = @@ERROR
		
		IF @intErrorCode = 0
		BEGIN
			DELETE FROM
				Hishop_BrandCategories
			WHERE
				BrandId = @BrandId
				
			SET @intErrorCode = @@ERROR
		END
			
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
			COMMIT TRAN
		END
		ELSE
			ROLLBACK TRAN
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN
			
		INSERT INTO 
			Hishop_BrandCategories(BrandName, Logo, CompanyUrl, Description)
		VALUES 
			(@BrandName, @Logo, @CompanyUrl, @Description)
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
		UPDATE 
			Hishop_BrandCategories 
		SET 
			BrandName = @BrandName,
			Logo = @Logo,
			CompanyUrl = @CompanyUrl,
			Description = @Description
		WHERE BrandId = @BrandId
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_BrandCategory_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_BrandCategory_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_BrandCategory_CreateUpdateDelete] 
	(
		@BrandId INT = NULL,
		@BrandName NVARCHAR(50) = NULL,
		@Logo NVARCHAR(255) = NULL,
		@CompanyUrl NVARCHAR(255) = NULL,
		@Description NVARCHAR(4000) = NULL,
		@Action INT,
		@Status INT OUTPUT
	)
AS
	SET @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN -- 同时修改商品品牌
	
		SET XACT_ABORT ON
		DECLARE @intErrorCode INT
		
		BEGIN TRAN
		
		UPDATE Hishop_Products SET BrandId = 0 WHERE BrandId = @BrandId
		SET @intErrorCode = @@ERROR
		
		IF @intErrorCode = 0
		BEGIN
			DELETE FROM
				Hishop_BrandCategories
			WHERE
				BrandId = @BrandId
				
			SET @intErrorCode = @@ERROR
		END
			
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
			COMMIT TRAN
		END
		ELSE
			ROLLBACK TRAN
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN
			
		INSERT INTO 
			Hishop_BrandCategories(BrandName, Logo, CompanyUrl, Description)
		VALUES 
			(@BrandName, @Logo, @CompanyUrl, @Description)
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
		UPDATE 
			Hishop_BrandCategories 
		SET 
			BrandName = @BrandName,
			Logo = @Logo,
			CompanyUrl = @CompanyUrl,
			Description = @Description
		WHERE BrandId = @BrandId
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_co_GetOrderInfo]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_co_GetOrderInfo]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[sp_co_GetOrderInfo]
(
  @OrderId nvarchar(50) = null
)
as
 BEGIN
 	SELECT * FROM Hishop_Orders Where OrderId = @OrderId
    SELECT  * FROM Hishop_OrderOptions Where OrderId = @OrderId 
    SELECT  * FROM Hishop_OrderGifts Where OrderId = @OrderId 
	SELECT  o.*,
	(select stock from hishop_products where productid=o.productId)  as Stock FROM Hishop_OrderItems o Where o.OrderId = @OrderId 
 END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_ReviewProducts_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_ReviewProducts_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_ReviewProducts_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@Total int = 0 output,
	@CategoryId INT = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForSearch
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ProductId INT,
        ProductName Nvarchar(200),
        SKU Nvarchar(50),
        AddedDate DateTime,
        SalePrice Money,
        Stock INT,
        Recommended BIT,
        Latest BIT,
        Hotsale BIT,
        SpecialOffer BIT,
        VistiCounts INT,
        ReviewCounts INT,
	    ReviewId int,
        ReviewDate DateTime,
        UserId int,
        UserName Nvarchar(200)
	)

	-- 如果指定了商品分类，则搜索商品分类
	IF @CategoryId > 0
	BEGIN
		-- 匹配当前分类的Path
		DECLARE @Path VARCHAR(4000)
		DECLARE @ParmDefinition NVARCHAR(500)
		
		SELECT 
			@ParmDefinition = N''@CategoryId INT,@Path VARCHAR(4000)'', @Path = Path + LTRIM(RTRIM(STR(@CategoryId))) + '','' 
		FROM 
			Hishop_Categories 
		WHERE 
			CategoryId = @CategoryId
			
		INSERT INTO #PageIndexForSearch (ProductId,ProductName,SKU,AddedDate,SalePrice,Stock, Recommended, Latest, Hotsale, SpecialOffer, VistiCounts, ReviewCounts, ReviewId,ReviewDate,UserId,UserName) 
		EXEC sp_executesql @SqlPopulate, @ParmDefinition, @CategoryId, @Path		
	END
	ELSE
		INSERT INTO #PageIndexForSearch (ProductId,ProductName,SKU,AddedDate,SalePrice,Stock, Recommended, Latest, Hotsale, SpecialOffer, VistiCounts, ReviewCounts, ReviewId,ReviewDate,UserId,UserName) 
    Exec sp_executesql @sqlPopulate
    
		-- 第一层
		SELECT
		  p.[CategoryId]
		  ,p.[ProductId]
		  ,p.[BrandId]
		  ,p.[SKU]
		  ,p.[SupplierId]
		  ,p.[ProductName]
		  ,p.[ShortDescription]
		  ,p.[Unit]
		  ,p.[Weight]
		  ,p.[Description]
		  ,p.[Title]
		  ,p.[Meta_Description]
		  ,p.[Meta_Keywords]
		  ,p.[ThumbnailsUrl]
		  ,p.[InFocusImageUrl]
		  ,p.[Recommended]
		  ,p.[Latest]
		  ,p.[Hotsale]
		  ,p.[SpecialOffer]
		  ,p.[CostPrice]
		  ,p.[MarketPrice]
		  ,p.[Upselling]
		  ,p.[SalePrice]
		  ,p.[Stock]
		  ,p.[QuantityLimit]
		  ,p.[AddedDate]
		  ,p.[VistiCounts]
		  ,#PageIndexForSearch.ReviewCounts
          ,r.ReviewId
          ,r.ReviewText
          ,r.ReviewDate
          ,r.UserId
          ,(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = r.UserId) AS UserName 
		FROM 
		 Hishop_Products p (nolock)inner join Hishop_ProductReviews r on (r.productId=p.ProductId)
		,#PageIndexForSearch
		WHERE 
			r.ReviewId = #PageIndexForSearch.ReviewId AND
			#PageIndexForSearch.IndexId > @PageLowerBound AND
			#PageIndexForSearch.IndexId < @PageUpperBound
		ORDER BY
			#PageIndexForSearch.IndexId

		SET @Total = @@rowcount

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_ProductConsultation_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_ProductConsultation_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_ProductConsultation_Get] 
		(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@CategoryId INT = 0,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalProducts INT

	SET @TotalProducts = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ConsultationId int
	)
	
	-- 如果指定了商品分类，则搜索商品分类
	IF @CategoryId > 0
	BEGIN
		-- 匹配当前分类的Path
		DECLARE @Path VARCHAR(4000)
		DECLARE @ParmDefinition NVARCHAR(500)
		
		SELECT 
			@ParmDefinition = N''@CategoryId INT,@Path VARCHAR(4000)'', @Path = Path + LTRIM(RTRIM(STR(@CategoryId))) + '','' 
		FROM 
			Hishop_Categories 
		WHERE 
			CategoryId = @CategoryId
			
		INSERT INTO #PageIndexForSearch (ConsultationId) 
		EXEC sp_executesql @SqlPopulate, @ParmDefinition, @CategoryId, @Path		
	END
	ELSE
		INSERT INTO #PageIndexForSearch (ConsultationId)  EXEC sp_executesql @SqlPopulate
	
	SET @TotalProducts = @@ROWCOUNT
	
	SELECT
	  p.[CategoryId]
      ,p.[ProductId]
      ,p.[BrandId]
      ,p.[SKU]
      ,p.[SupplierId]
      ,p.[ProductName]
      ,p.[ShortDescription]
      ,p.[Unit]
      ,p.[Weight]
      ,p.[Description]
      ,p.[Title]
      ,p.[Meta_Description]
      ,p.[Meta_Keywords]
      ,p.[ThumbnailsUrl]
      ,p.[InFocusImageUrl]
      ,p.[Recommended]
      ,p.[Latest]
      ,p.[Hotsale]
      ,p.[SpecialOffer]
      ,p.[CostPrice]
      ,p.[MarketPrice]
      ,p.[Upselling]
      ,p.[SalePrice]
      ,p.[Stock]
      ,p.[QuantityLimit]
      ,p.[AddedDate]
      ,p.[VistiCounts]
      ,c.[ConsultationId]
	  ,c.[ConsultationText]
      ,c.[ConsultationDate]
      ,c.[ReplyText]
      ,c.[UserName]
      ,c.[ReplyUserId]
      ,c.[Userid]
	  ,c.[ReplyDate]
      ,(SELECT UserName FROM vw_Users_FullUser WHERE hi_UserId = c.ReplyUserId) AS ReplyUserName
	FROM 
		Hishop_Products p (nolock) inner join Hishop_ProductConsultations c on (p.productId=c.ProductId),
		#PageIndexForSearch
	WHERE 
		c.ConsultationId = #PageIndexForSearch.ConsultationId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId

END

IF (@IsCount = 1)
	SELECT @TotalProducts' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Products_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Products_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Products_Get] 
		(
		@PageIndex INT,
		@PageSize INT,
		@IsCount BIT,
		@CategoryId INT = 0,
		@SqlPopulate NTEXT
	)

AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound INT
	DECLARE @PageUpperBound INT
	DECLARE @RowsToReturn INT
	DECLARE @TotalProducts INT

	SET @TotalProducts = 0
	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1
	
	-- Create a temp table to store the select results
	CREATE TABLE #PageIndexForSearch 
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		ProductId INT,
        ProductName Nvarchar(200),
        SKU Nvarchar(50),
        AddedDate DateTime,
        SalePrice Money,
        Stock INT,
        Recommended BIT,
        Latest BIT,
        Hotsale BIT,
        SpecialOffer BIT,
        VistiCounts INT
	)
	
	-- 如果指定了商品分类，则搜索商品分类
	IF @CategoryId > 0
	BEGIN
		-- 匹配当前分类的Path
		DECLARE @Path VARCHAR(4000)
		DECLARE @ParmDefinition NVARCHAR(500)
		
		SELECT 
			@ParmDefinition = N''@CategoryId INT,@Path VARCHAR(4000)'', @Path = Path + ''|'' 
		FROM 
			Hishop_Categories 
		WHERE 
			CategoryId = @CategoryId
			
		INSERT INTO #PageIndexForSearch (ProductId,ProductName,SKU,AddedDate,SalePrice,Stock, Recommended, Latest, Hotsale, SpecialOffer, VistiCounts) 
		EXEC sp_executesql @SqlPopulate, @ParmDefinition, @CategoryId, @Path		
	END
	ELSE
		INSERT INTO #PageIndexForSearch (ProductId,ProductName,SKU,AddedDate,SalePrice,Stock, Recommended, Latest, Hotsale, SpecialOffer, VistiCounts)   EXEC sp_executesql @SqlPopulate
	
	SET @TotalProducts = @@ROWCOUNT
	
	SELECT
	  p.[CategoryId]
      ,p.[ProductId]
      ,p.[BrandId]
      ,p.[SKU]
      ,p.[SupplierId]
      ,p.[ProductName]
      ,p.[ShortDescription]
      ,p.[Unit]
      ,p.[Weight]
      ,p.[Description]
      ,p.[Title]
      ,p.[Meta_Description]
      ,p.[Meta_Keywords]
      ,p.[ThumbnailsUrl]
      ,p.[InFocusImageUrl]
      ,p.[Recommended]
      ,p.[Latest]
      ,p.[Hotsale]
      ,p.[SpecialOffer]
      ,p.[CostPrice]
      ,p.[MarketPrice]
      ,p.[Upselling]
      ,p.[SalePrice]
      ,p.[Stock]
      ,p.[QuantityLimit]
      ,p.[AddedDate]
      ,p.[VistiCounts]
	FROM 
		Hishop_Products p (nolock),
		#PageIndexForSearch
	WHERE 
		p.ProductId = #PageIndexForSearch.ProductId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId

END

IF (@IsCount = 1)
	SELECT @TotalProducts' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_Category_Delete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_Category_Delete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_Category_Delete]
(
	@CategoryId INT,
	@Status INT OUTPUT
)
AS
Declare @Err As int, @Count INT, @DisplaySequence INT
DECLARE @Path nvarchar(4000)

SET XACT_ABORT ON
Begin Tran

CREATE TABLE #tempTable (CategoryId INT)

SELECT @Err = 0, @Status = 99, @Path = Path, @DisplaySequence = DisplaySequence FROM Hishop_Categories WHERE CategoryId = @CategoryId
INSERT INTO #tempTable SELECT CategoryId FROM Hishop_Categories WHERE CategoryId = @CategoryId OR Path LIKE '''' + @Path + ''|%''

SET @Count = @@ROWCOUNT

-- 删除自身和所有子分类
DELETE From Hishop_Categories Where CategoryId IN (SELECT CategoryId FROM #tempTable)

-- 修改商品分类的编号为0，表示未分类
UPDATE Hishop_Products SET CategoryId = 0 WHERE CategoryId IN (SELECT CategoryId FROM #tempTable)

-- 删除商品扩展分类
DELETE FROM Hishop_ProductExtendCategories WHERE CategoryId IN (SELECT CategoryId FROM #tempTable)

--更新其他记录的DisplaySequence
UPDATE Hishop_Categories Set DisplaySequence = DisplaySequence -@Count Where DisplaySequence > @DisplaySequence 

DROP TABLE #tempTable

  Commit Tran
  SET @Status = 0' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_Category_Create]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_Category_Create]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_Category_Create]
	(
		@Name NVARCHAR(100) = NULL,
		@DisplaySequence INT = NULL,
		@IconUrl NVARCHAR(255) = NULL,
		@IndexChar CHAR(1) = NULL,
		@Meta_Description NVARCHAR(1000) = NULL,
		@Meta_Keywords NVARCHAR(1000) = NULL,
		@Description NVARCHAR(1000) = NULL,
		@Notes NTEXT = NULL,
		@ParentCategoryId INT = NULL,
		@DisplayRecommend BIT = NULL,
		@DisplayLatest BIT = NULL,
		@DisplayHotsale BIT = NULL,
		@DisplaySpecial BIT = NULL,
		@RewriteName NVARCHAR(50) = NULL,
		@TypeId INT = NULL,
		@Status INT OUTPUT
	)
AS
Declare @Err As int
SELECT @Err=0, @Status = 99

SET XACT_ABORT ON
Begin Tran
IF @DisplaySequence IS NULL OR @DisplaySequence <= 0
	SET @DisplaySequence = 1
	
IF @ParentCategoryId IS NULL OR @ParentCategoryId < 0
	SET @ParentCategoryId = 0
	
--通过现有记录获取栏目ID
Declare @CategoryId As int
Declare @Depth As int

CREATE TABLE #tempTable (DisplaySequence INT)
DECLARE @subQuery nvarchar(4000)

Select @CategoryId = Max(CategoryId) From Hishop_Categories
IF @CategoryId Is Not Null
	Set @CategoryId = @CategoryId+1
Else
	Set @CategoryId = 1

--判断是否是顶级栏目，设置其Path和Order
Declare @Path As nvarchar(4000)
Declare @Order As int

IF @ParentCategoryId = 0
Begin
	SET @subQuery = ''SELECT TOP '' + LTRIM(RTRIM(str(@DisplaySequence))) + '' DisplaySequence FROM Hishop_Categories WHERE Depth = 1 ORDER BY DisplaySequence ASC''
	
	INSERT INTO #tempTable EXEC sp_executesql @subQuery
	Select @Order = Max(DisplaySequence) From #tempTable
	
	IF @Order Is Null
		Set @Order = 1

	Set @Path =Ltrim(RTRIM(Str(@CategoryId)))
	Set @Depth = 1
End
Else
Begin
	--获取父节点的路径和深度
	Select @Path = [Path] ,@Depth = Depth From Hishop_Categories Where CategoryId=@ParentCategoryId
	IF @Path Is Null
	Begin
		Set @Err = 1
		Goto theEnd
	End

	SET @subQuery = ''SELECT TOP '' + LTRIM(RTRIM(str(@DisplaySequence))) + '' DisplaySequence FROM Hishop_Categories WHERE ParentCategoryId = '' + LTRIM(RTRIM(str(@ParentCategoryId))) + '' ORDER BY DisplaySequence ASC''
	
	INSERT INTO #tempTable EXEC sp_executesql @subQuery
	Select @Order = Max(DisplaySequence) From #tempTable
	
	IF @Order Is Null
	Begin 
		SELECT @Order = DisplaySequence + 1 FROM Hishop_Categories WHERE CategoryId = @ParentCategoryId
	End 

	Set @Path = @Path + ''|'' + Ltrim(RTRIM(Str(@CategoryId)))
	Set @Depth = @Depth+1
End

--更新当前要插入节点后所有节点的序号
Update Hishop_Categories Set DisplaySequence = DisplaySequence +1 Where DisplaySequence >= @Order

Insert Into Hishop_Categories(
	[Name], DisplaySequence, IconUrl, IndexChar, Meta_Description, Meta_Keywords, Description,Notes, TypeId,
	ParentCategoryId, Depth, Path, DisplayRecommend, DisplayLatest, DisplayHotsale, DisplaySpecial, RewriteName
) 
Values(
	@Name, @Order, @IconUrl, @IndexChar, @Meta_Description, @Meta_Keywords, @Description,@Notes, @TypeId,
	@ParentCategoryId, @Depth, @Path, @DisplayRecommend, @DisplayLatest, @DisplayHotsale, @DisplaySpecial, @RewriteName
)

DROP TABLE #tempTable

IF @@Error<>0 
Begin
	Set @Err=1
	Goto theEnd
End

theEnd:
IF @Err=0
Begin
	Commit Tran
	SET @Status = 0
	Return @CategoryId
End
Else
Begin
    Rollback Tran
	Return 0
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_Category_Update]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_Category_Update]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_Category_Update]
(
	@CategoryId INT,
	@Name NVARCHAR(100) = NULL,
	@IconUrl NVARCHAR(255) = NULL,
	@IndexChar CHAR(1) = NULL,
	@Meta_Description NVARCHAR(1000) = NULL,
	@Meta_Keywords NVARCHAR(1000) = NULL,
	@Description NVARCHAR(1000) = NULL,
	@Notes NTEXT = NULL,
	@DisplayRecommend BIT = NULL,
	@DisplayLatest BIT = NULL,
	@DisplayHotsale BIT = NULL,
	@DisplaySpecial BIT = NULL,
	@RewriteName NVARCHAR(50) = NULL,
	@TypeId INT = NULL
)
AS
UPDATE 
			Hishop_Categories 
		SET 
			[Name] = @Name,
			IconUrl = @IconUrl,
			IndexChar = @IndexChar,
			Meta_Description = @Meta_Description,
			Meta_Keywords = @Meta_Keywords,
			Description = @Description,
			Notes = @Notes,
			DisplayRecommend = @DisplayRecommend,
			DisplayLatest = @DisplayLatest,
			DisplayHotsale = @DisplayHotsale,
			DisplaySpecial = @DisplaySpecial,
			RewriteName = @RewriteName,
			TypeId = @TypeId
		WHERE CategoryId = @CategoryId' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_Category_SwapDisplaySequence]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_Category_SwapDisplaySequence]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_Category_SwapDisplaySequence]
	(
		@CategoryId INT,
		@ZIndex INT
	)
AS
	-- @ZIndex = 0，向前移动，@ZIndex = 1，向后移动
	DECLARE @Path nvarchar(4000)
	DECLARE @ParentCategoryId INT, @DisplaySequence INT
	
	DECLARE @swap_Path nvarchar(4000)
	DECLARE @swap_CategoryId INT
	
	SELECT @Path = Path, @ParentCategoryId = ParentCategoryId, @DisplaySequence = DisplaySequence FROM Hishop_Categories WHERE CategoryId = @CategoryId
	IF @Path IS NULL OR @ParentCategoryId IS NULL
		RETURN
		
	IF @ZIndex = 0
		SELECT TOP 1 @swap_Path = Path, @swap_CategoryId = CategoryId FROM Hishop_Categories WHERE ParentCategoryId = @ParentCategoryId AND DisplaySequence < @DisplaySequence ORDER BY DisplaySequence DESC
	ELSE
		SELECT TOP 1 @swap_Path = Path, @swap_CategoryId = CategoryId FROM Hishop_Categories WHERE ParentCategoryId = @ParentCategoryId AND DisplaySequence > @DisplaySequence ORDER BY DisplaySequence ASC
	
	IF @swap_Path IS NULL OR @swap_CategoryId IS NULL
		RETURN;
	
	SET XACT_ABORT ON
	BEGIN TRAN
	
	DECLARE @tempTable TABLE (CategoryId INT)
	DECLARE @Count INT, @SwapCount INT
	
	INSERT INTO @tempTable SELECT CategoryId FROM Hishop_Categories WHERE CategoryId = @CategoryId OR Path LIKE '''' + @Path + ''|%''
	SET @Count = @@ROWCOUNT
	
	IF @ZIndex = 0
	BEGIN
		UPDATE Hishop_Categories SET DisplaySequence = DisplaySequence + @Count WHERE CategoryId = @swap_CategoryId OR Path LIKE '''' + @swap_Path + ''|%''
		SET @SwapCount = @@ROWCOUNT
		UPDATE Hishop_Categories SET DisplaySequence = DisplaySequence - @SwapCount WHERE CategoryId IN (SELECT CategoryId FROM @tempTable)
	END
	ELSE
	BEGIN
		UPDATE Hishop_Categories SET DisplaySequence = DisplaySequence - @Count WHERE CategoryId = @swap_CategoryId OR Path LIKE '''' + @swap_Path + ''|%''
		SET @SwapCount = @@ROWCOUNT
		UPDATE Hishop_Categories SET DisplaySequence = DisplaySequence + @SwapCount WHERE CategoryId IN (SELECT CategoryId FROM @tempTable)
	END
	
	COMMIT TRAN' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_ArticleCategory_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_ArticleCategory_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_ArticleCategory_CreateUpdateDelete]
	(
		@CategoryId INT = NULL,
		@Name NVARCHAR(100) = NULL,
		@DisplaySequence INT = NULL,
		@IconUrl NVARCHAR(255) = NULL,
		@Description NVARCHAR(1000) = NULL,
		@Action INT,
		@Status INT OUTPUT
	)
AS
	
	-- 初始化信息
	SELECT @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN -- 同时删除分类下的文章

		DELETE FROM Hishop_Articles WHERE CategoryId = @CategoryId
		DELETE FROM Hishop_ArticleCategories WHERE CategoryId = @CategoryId
		
		IF @@ROWCOUNT >= 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN
		
		--如果排序编号在此兄弟节点间存在,则修改分类中兄弟节点的其它的排序编号
		IF EXISTS(SELECT DisplaySequence FROM Hishop_ArticleCategories WHERE DisplaySequence = @DisplaySequence) 
		-- 将大于或等于其兄弟节点的排序号加1
			UPDATE Hishop_ArticleCategories SET DisplaySequence = DisplaySequence + 1 WHERE DisplaySequence >= @DisplaySequence
		
		INSERT INTO Hishop_ArticleCategories
			([Name], DisplaySequence, IconUrl, Description)
		VALUES 
			(@Name, @DisplaySequence, @IconUrl, @Description)
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
		-- 如果排序编号在此兄弟节点间存在,则修改分类中兄弟节点的其它的排序编号
		IF EXISTS(SELECT DisplaySequence FROM Hishop_ArticleCategories WHERE DisplaySequence = @DisplaySequence) 
		-- 将大于或等于其兄弟节点的排序号加1
			UPDATE Hishop_ArticleCategories SET DisplaySequence = DisplaySequence + 1 WHERE DisplaySequence >=@DisplaySequence
		
		-- 修改分类信息
		UPDATE 
			Hishop_ArticleCategories 
		SET 
			[Name] = @Name,
			DisplaySequence = @DisplaySequence,
			IconUrl = @IconUrl,
			Description = @Description
		WHERE CategoryId = @CategoryId
		
		IF @@ROWCOUNT >= 1
			SET @Status = 0
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_Article_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_Article_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_Article_CreateUpdateDelete]
	(
		@CategoryId INT = NULL,
		@ArticleId INT = NULL,
		@Title NVARCHAR(200) = NULL,
		@Description NVARCHAR(1000) = NULL,
		@Content NTEXT = NULL,
		@AddedDate DATETIME= NULL,
		@UserId INT = NULL,
		@Action INT,
		@Status INT OUTPUT
	)
AS
	SET @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN
	
		DELETE FROM Hishop_Articles WHERE CategoryId = @CategoryId OR ArticleId = @ArticleId
			
		IF @@ROWCOUNT > 0
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN

		INSERT INTO 
			Hishop_Articles(CategoryId, Title, Description, Content, AddedDate, UserId)
		VALUES 
			(@CategoryId, @Title, @Description, @Content, @AddedDate, @UserId)
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
		UPDATE 
			Hishop_Articles 
		SET 
			CategoryId = @CategoryId,
			AddedDate = @AddedDate,
			Title = @Title,
			Description = @Description,
			Content = @Content
		WHERE ArticleId = @ArticleId
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_OrderLookupItems_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_OrderLookupItems_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[sp_OrderLookupItems_CreateUpdateDelete]
(
@LookupListId int	 = null,
@LookupItemId 	int= null,
@Name	nvarchar(100) = null,
@IsUserInputRequired bit	 = null,
@UserInputTitle	nvarchar (20) = null,
@AllowInputNothing	bit	 = null,
@AppendMoney money = null,
@CalculateMode int	= null,
@Remark	nvarchar(100) = null,
@Action INT,
@Status INT OUTPUT
)
as 
 --初始化信息
	SELECT @Status = 99
   IF  @Action = 2 --删除
   BEGIN
     DELETE FROM Hishop_OrderLookupItems 
     WHERE LookupItemId =@LookupItemId
     IF @@ROWCOUNT =1
        Set @Status = 0
     RETURN
   END
  
   IF  @Action = 0 --创建
   BEGIN
   INSERT INTO Hishop_OrderLookupItems
     (LookupListId,[Name],IsUserInputRequired,UserInputTitle,AllowInputNothing,
     AppendMoney,CalculateMode,Remark)
    VALUES(@LookupListId,@Name,@IsUserInputRequired,@UserInputTitle,@AllowInputNothing,
     @AppendMoney,@CalculateMode,@Remark)
    IF @@ROWCOUNT =1
        Set @Status = 0
    RETURN
   END 
   
 IF @Action = 1 -- 修改
  BEGIN 
  UPDATE Hishop_OrderLookupItems SET
  LookupListId = @LookupListId,
  [Name] = @Name, IsUserInputRequired = @IsUserInputRequired,
  UserInputTitle = @UserInputTitle,AllowInputNothing = @AllowInputNothing,
  AppendMoney = @AppendMoney,CalculateMode = @CalculateMode,Remark=@Remark
  WHERE LookupItemId =@LookupItemId
   IF @@ROWCOUNT = 1
			SET @Status = 0
  RETURN
  END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_OrderLookupLists_CreateUpDateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_OrderLookupLists_CreateUpDateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_OrderLookupLists_CreateUpDateDelete] -- OrderLookupLists  定单可选项添加 删除修改
(
   @LookupListId Int=null,
   @Name Nvarchar(100)=null,
   @SelectMode Int =null,
   @Description NvarChar(4000)=null,
   @Action INT,
   @Status INT OUTPUT
)
as 
   SET @Status = 99

    IF @Action = 2 -- 删除
    BEGIN -- 同时删除可选项属性值
	
    SET XACT_ABORT ON
      DECLARE @intErrorCode INT
       BEGIN TRAN
          DELETE FROM  Hishop_OrderLookupItems Where  LookupListId = @LookupListId
          SET @intErrorCode = @@ERROR
	    IF @intErrorCode = 0
	    
        BEGIN
          DELETE FROM Hishop_OrderLookupLists
          WHERE LookupListId = @LookupListId
         SET @intErrorCode = @@ERROR
        END
        
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
			COMMIT TRAN
		END
		ELSE
			ROLLBACK TRAN
		RETURN
   END
 
   IF @Action =0 --创建
   BEGIN 
   
       INSERT INTO Hishop_OrderLookupLists([Name],SelectMode,Description)
       VALUES(@Name,@SelectMode,@Description)
       IF @@ROWCOUNT = 1
			SET @Status = 0
			
		RETURN
   END 
  
  IF @Action = 1 -- 修改
  BEGIN
    IF EXISTS (SELECT * FROM Hishop_OrderLookupLists WHERE (LOWER([Name]) = LOWER(@Name)) AND  LookupListId !=@LookupListId)
     BEGIN
	    SET @Status = 1
	  RETURN
	 END 
  
    UpDate Hishop_OrderLookupLists 
     Set
       [Name]= @Name,SelectMode = @SelectMode,Description = @Description
    WHERE 
       LookupListId = @LookupListId

    IF @@ROWCOUNT = 1
		SET @Status = 0
	 	
	RETURN
  END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Discount_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Discount_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Discount_Get]
  (
 @DateTime DateTime
)
as
BEGIN

SELECT ps.*,pd.Amount ,pd.DiscountValue,pd.ValueType
 From Hishop_PromoteSales ps 
INNER JOIN Hishop_PromoteSales_Discount pd
 ON ps.ActivityId = pd.ActivityId Where ps.ClosingTime >@DateTime AND ps.StartTime<@DateTime
Order By Amount DESC
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_AnyDataInTables]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_AnyDataInTables]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_AnyDataInTables]
    @TablesToCheck int
AS
BEGIN
    -- Check Membership table if (@TablesToCheck & 1) is set
    IF ((@TablesToCheck & 1) <> 0 AND
        (EXISTS (SELECT name FROM sysobjects WHERE (name = N''vw_aspnet_MembershipUsers'') AND (type = ''V''))))
    BEGIN
        IF (EXISTS(SELECT TOP 1 UserId FROM dbo.aspnet_Membership))
        BEGIN
            SELECT N''aspnet_Membership''
            RETURN
        END
    END

    -- Check aspnet_Roles table if (@TablesToCheck & 2) is set
    IF ((@TablesToCheck & 2) <> 0  AND
        (EXISTS (SELECT name FROM sysobjects WHERE (name = N''vw_aspnet_Roles'') AND (type = ''V''))) )
    BEGIN
        IF (EXISTS(SELECT TOP 1 RoleId FROM dbo.aspnet_Roles))
        BEGIN
            SELECT N''aspnet_Roles''
            RETURN
        END
    END

    -- Check aspnet_Profile table if (@TablesToCheck & 4) is set
    IF ((@TablesToCheck & 4) <> 0  AND
        (EXISTS (SELECT name FROM sysobjects WHERE (name = N''vw_aspnet_Profiles'') AND (type = ''V''))) )
    BEGIN
        IF (EXISTS(SELECT TOP 1 UserId FROM dbo.aspnet_Profile))
        BEGIN
            SELECT N''aspnet_Profile''
            RETURN
        END
    END

    -- Check aspnet_Users table if (@TablesToCheck & 1,2,4 & 8) are all set
    IF ((@TablesToCheck & 1) <> 0 AND
        (@TablesToCheck & 2) <> 0 AND
        (@TablesToCheck & 4) <> 0 AND
        (@TablesToCheck & 8) <> 0 AND
        (@TablesToCheck & 32) <> 0 AND
        (@TablesToCheck & 128) <> 0 AND
        (@TablesToCheck & 256) <> 0 AND
        (@TablesToCheck & 512) <> 0 AND
        (@TablesToCheck & 1024) <> 0)
    BEGIN
        IF (EXISTS(SELECT TOP 1 UserId FROM dbo.aspnet_Users))
        BEGIN
            SELECT N''aspnet_Users''
            RETURN
        END
        IF (EXISTS(SELECT TOP 1 ApplicationId FROM dbo.aspnet_Applications))
        BEGIN
            SELECT N''aspnet_Applications''
            RETURN
        END
    END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Profile_GetProperties]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Profile_GetProperties]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Profile_GetProperties]
    @ApplicationName      nvarchar(256),
    @UserName             nvarchar(256),
    @CurrentTimeUtc       datetime
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN

    DECLARE @UserId uniqueidentifier
    SELECT  @UserId = NULL

    SELECT @UserId = UserId
    FROM   dbo.aspnet_Users
    WHERE  ApplicationId = @ApplicationId AND LoweredUserName = LOWER(@UserName)

    IF (@UserId IS NULL)
        RETURN
    SELECT TOP 1 PropertyNames, PropertyValuesString, PropertyValuesBinary
    FROM         dbo.aspnet_Profile
    WHERE        UserId = @UserId

    IF (@@ROWCOUNT > 0)
    BEGIN
        UPDATE dbo.aspnet_Users
        SET    LastActivityDate=@CurrentTimeUtc
        WHERE  UserId = @UserId
    END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Profile_DeleteInactiveProfiles]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Profile_DeleteInactiveProfiles]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Profile_DeleteInactiveProfiles]
    @ApplicationName        nvarchar(256),
    @ProfileAuthOptions     int,
    @InactiveSinceDate      datetime
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
    BEGIN
        SELECT  0
        RETURN
    END

    DELETE
    FROM    dbo.aspnet_Profile
    WHERE   UserId IN
            (   SELECT  UserId
                FROM    dbo.aspnet_Users u
                WHERE   ApplicationId = @ApplicationId
                        AND (LastActivityDate <= @InactiveSinceDate)
                        AND (
                                (@ProfileAuthOptions = 2)
                             OR (@ProfileAuthOptions = 0 AND IsAnonymous = 1)
                             OR (@ProfileAuthOptions = 1 AND IsAnonymous = 0)
                            )
            )

    SELECT  @@ROWCOUNT
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Profile_GetNumberOfInactiveProfiles]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Profile_GetNumberOfInactiveProfiles]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Profile_GetNumberOfInactiveProfiles]
    @ApplicationName        nvarchar(256),
    @ProfileAuthOptions     int,
    @InactiveSinceDate      datetime
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
    BEGIN
        SELECT 0
        RETURN
    END

    SELECT  COUNT(*)
    FROM    dbo.aspnet_Users u, dbo.aspnet_Profile p
    WHERE   ApplicationId = @ApplicationId
        AND u.UserId = p.UserId
        AND (LastActivityDate <= @InactiveSinceDate)
        AND (
                (@ProfileAuthOptions = 2)
                OR (@ProfileAuthOptions = 0 AND IsAnonymous = 1)
                OR (@ProfileAuthOptions = 1 AND IsAnonymous = 0)
            )
END' 
END
GO
/****** Object:  View [dbo].[vw_aspnet_Profiles]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[vw_aspnet_Profiles]') AND OBJECTPROPERTY(id, N'IsView') = 1)
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vw_aspnet_Profiles]
  AS SELECT [dbo].[aspnet_Profile].[UserId], [dbo].[aspnet_Profile].[LastUpdatedDate],
      [DataSize]=  DATALENGTH([dbo].[aspnet_Profile].[PropertyNames])
                 + DATALENGTH([dbo].[aspnet_Profile].[PropertyValuesString])
                 + DATALENGTH([dbo].[aspnet_Profile].[PropertyValuesBinary])
  FROM [dbo].[aspnet_Profile]'
GO
/****** Object:  View [dbo].[vw_Users_FullUser]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[vw_Users_FullUser]') AND OBJECTPROPERTY(id, N'IsView') = 1)
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vw_Users_FullUser]
AS
SELECT   au.UserName, au.IsAnonymous, au.UserId, au.LastActivityDate, am.PasswordQuestion, am.Email, am.IsApproved, 
                am.CreateDate, am.LastLoginDate, am.LastPasswordChangedDate, am.IsLockedOut, am.LastLockoutDate, am.Comment, 
                cu.UserId AS hi_UserId, cu.ForceLogin AS hi_ForceLogin, cu.UserAccountStatus AS hi_UserAccountStatus, 
                cu.AppUserToken AS hi_AppUserToken, am.PasswordFormat, cu.LastActivity AS hi_LastActivity, 
                cu.LastAction AS hi_LastAction, fup.IsIgnored, fup.PublicToken, 
                fup.PropertyNames AS UserPropertyNames, fup.PropertyValues AS UserPropertyValues, 
                fup.EnableDisplayInMemberList, fup.EnablePrivateMessages, fup.EnableOnlineStatus, 
                fup.EnableEmail, fup.EnableHtmlEmail, ap.PropertyNames AS ProfileNames, fup.Address, fup.QQ, fup.MSN, fup.TelPhone, fup.CellPhone, ap.PropertyValuesString, 
                ap.PropertyValuesBinary, fup.Points AS UserPoints, fup.OrderNumber, fup.Expenditure, 
                fup.EnableTradePassword, fup.TradePasswordFormat, fup.RealName, fup.RegionId, fup.TradePasswordSalt,
                fup.UserRank,fup.ParentUserId,fup.ReferralUserId,fup.Agent_Expires,fup.Agent_IsUrlBindApproved,fup.Agent_IsShowTQServer, fup.Agent_TQServices,
                fup.Agent_SiteUrl,fup.Agent_LogoUrl,fup.Agent_Footer,fup.Agent_SiteName, fup.Agent_SiteDescription, fup.Agent_Theme,
                fup.BirthDate, fup.Gender, fup.Balance, fup.DeductMoney
FROM      dbo.aspnet_Membership AS am WITH (nolock) INNER JOIN
                dbo.aspnet_Users AS au WITH (nolock) ON am.UserId = au.UserId INNER JOIN
                dbo.Hishop_Users AS cu WITH (nolock) ON au.UserId = cu.MembershipId INNER JOIN
                dbo.Hishop_UserProfile AS fup WITH (nolock) ON cu.UserId = fup.UserId LEFT OUTER JOIN
                dbo.aspnet_Profile AS ap WITH (nolock) ON au.UserId = ap.UserId
WHERE   (cu.Deleted = 0)'
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_ShippingMode_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_ShippingMode_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_ShippingMode_Get]
(
  @ModeId Int,
  @IncludeDetail BIT = 0
)
AS
BEGIN
  SELECT * FROM Hishop_ShippingTypes Where ModeId =@ModeId
  IF @IncludeDetail = 1
   BEGIN
	 SELECT ShippingModeId, PaymentModeId FROM Hishop_ShippingPayment WHERE ShippingModeId = @ModeId 
     SELECT GroupId,ModeId,Price,AddPrice FROM Hishop_ShippingTypeGroups Where ModeId =@ModeId
     SELECT sr.ModeId,sr.GroupId,sr.RegionId,
     (SELECT RegionName FROM Hishop_Regions Where RegionId=sr.RegionId) as RegionName
     FROM Hishop_ShippingRegions sr
     Where sr.ModeId =@ModeId
 END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_ShippingMode_Update]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_ShippingMode_Update]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[sp_cs_ShippingMode_Update]
(
 @ModeId INT =null,
 @Name nvarchar(100),
 @Weight INT,	
 @AddWeight INT =null,
 @Price money,
 @AddPrice money =null,
 @Description nvarchar(4000)=null,
 @DisplaySequence int,
 @Status INT Output
)
as 
DECLARE @intErrorCode INT
	SELECT @Status = 99, @intErrorCode = 0
BEGIN TRAN
  --如果序号为空 则直接将序号设置为最大值加一
   IF  @DisplaySequence IS NUll
      SET @DisplaySequence = (Select Max(DisplaySequence) From Hishop_ShippingTypes) + 1
   -- 如果不为空则将 将表中现有的大于设置序号的值增加1
   Else IF @DisplaySequence != (Select DisplaySequence  From Hishop_ShippingTypes where ModeId=@ModeId)
      UPDATE Hishop_ShippingTypes Set DisplaySequence = DisplaySequence + 1 where DisplaySequence >= @DisplaySequence 
   
   Update Hishop_ShippingTypes 
   SET [Name]=@Name,Weight=@Weight,AddWeight =@AddWeight,Price=@Price ,AddPrice=@AddPrice , Description =@Description
   Where ModeId=@ModeId
   SET @intErrorCode = @intErrorCode + @@ERROR
   

   IF @intErrorCode = 0
   BEGIN
    DELETE FROM Hishop_ShippingRegions Where ModeId=@ModeId
    SET @intErrorCode = @intErrorCode + @@ERROR
   END
   IF @intErrorCode = 0
    BEGIN
       DELETE FROM Hishop_ShippingTypeGroups Where ModeId=@ModeId
   END
  IF @intErrorCode = 0
	BEGIN
		COMMIT TRAN
		SET @Status = 0
	END
	ELSE
		ROLLBACK TRAN' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_ShippingModes_Delete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_ShippingModes_Delete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[sp_cs_ShippingModes_Delete]
(
  @ModeId Int,
  @Status Int OUTPUT
)
As
    DECLARE @intErrorCode INT
	SELECT @Status = 99, @intErrorCode = 0
BEGIN
    IF @intErrorCode = 0
    BEGIN
	   DELETE FROM Hishop_ShippingRegions Where ModeId=@ModeId
       SET @intErrorCode = @intErrorCode + @@ERROR
    END

    IF @intErrorCode = 0
    BEGIN
	   DELETE FROM Hishop_ShippingTypeGroups Where ModeId=@ModeId
       SET @intErrorCode = @intErrorCode + @@ERROR
    END
 
   IF @intErrorCode = 0
    BEGIN
	    DELETE FROM Hishop_ShippingTypes Where ModeId=@ModeId
        SET @intErrorCode = @intErrorCode + @@ERROR
    END
    
    IF @intErrorCode = 0
    BEGIN
	    DELETE FROM Hishop_ShippingPayment Where ShippingModeId=@ModeId
        SET @intErrorCode = @intErrorCode + @@ERROR
    END

   IF @intErrorCode = 0
	BEGIN
		SET @Status = 0
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_ShippingMode_Sequence]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_ShippingMode_Sequence]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_ShippingMode_Sequence]
(
 @ModeId INT ,
 @Sort INT  -- 是升 还是降 1 表示升 2表示降
)
as

 --  当前要修改的序号
	 DECLARE @oldSequence INT
	 -- 要修改成的序号
	 DECLARE @newSequence INT
	 -- 和当前对换的编号
	 DECLARE @oModeId Int
 --升
 IF @Sort =1
 BEGIN
  Select @oldSequence = DisplaySequence FROM Hishop_ShippingTypes where ModeId =@ModeId

  SELECT @newSequence = DisplaySequence FROM Hishop_ShippingTypes 
  WHERE ModeId = (Select TOP 1 ModeId From Hishop_ShippingTypes Where DisplaySequence <@oldSequence 
    Order by DisplaySequence DESC)

  SELECT @oModeId = (Select TOp 1 ModeId From Hishop_ShippingTypes Where DisplaySequence <@oldSequence
   Order by DisplaySequence DESC)

  IF NOT @newSequence IS NULL
    BEGIN
      Update Hishop_ShippingTypes Set DisplaySequence = @newSequence Where ModeId =@ModeId
    END
  IF NOT @oModeId IS NULL
    BEGIN
      Update Hishop_ShippingTypes Set DisplaySequence = @oldSequence Where modeId =@oModeId
     END
 END

 -- 降
IF @Sort =0

BEGIN
  Select @oldSequence = DisplaySequence FROM Hishop_ShippingTypes where ModeId =@ModeId

  SELECT @newSequence = DisplaySequence FROM Hishop_ShippingTypes 
  WHERE ModeId = (Select TOp 1 ModeId From Hishop_ShippingTypes Where DisplaySequence >@oldSequence 
    Order by DisplaySequence Asc)
  

  SELECT @oModeId = (Select TOp 1 ModeId From Hishop_ShippingTypes Where DisplaySequence >@oldSequence
  Order by DisplaySequence Asc)
   

  IF  @newSequence IS NOT NULL
   BEGIN
      Update Hishop_ShippingTypes Set DisplaySequence = @newSequence Where ModeId =@ModeId
   END
  IF  @oModeId IS NOT NULL
   BEGIN
      Update Hishop_ShippingTypes Set DisplaySequence = @oldSequence Where modeId =@oModeId
    END
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_ShippingMode_Create]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_ShippingMode_Create]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[sp_cs_ShippingMode_Create]
(
 @ModeId int output,
 @Name nvarchar(100),
 @Weight int,	
 @AddWeight int =null,
 @Price money,
 @AddPrice money =null,
 @Description nvarchar(4000)=null,
 @DisplaySequence int,
 @Status int Output
)
as 
SET @Status = 99
BEGIN TRAN
--如果序号为空 则直接将序号设置为最大值加一
   IF  @DisplaySequence IS NUll
      SET @DisplaySequence = (Select Max(DisplaySequence) From Hishop_ShippingTypes) + 1
   -- 如果不为空则将 将表中现有的大于设置序号的值增加1
   ELSE
      UPDATE Hishop_ShippingTypes Set DisplaySequence = DisplaySequence + 1 where DisplaySequence >= @DisplaySequence 
 INSERT INTO Hishop_ShippingTypes
    ([Name],Weight,AddWeight,Price,AddPrice,Description,DisplaySequence)
 VALUES
    (@Name,@Weight,@AddWeight,@Price,@AddPrice,@Description,@DisplaySequence)
  SET @ModeId = @@IDENTITY
     IF @@ROWCOUNT = 1
	   SET @Status = 0
	 
COMMIT' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_PaymentMode_Sequence]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_PaymentMode_Sequence]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[sp_cs_PaymentMode_Sequence]
(
  @ModeId INT ,
  @Sort INT 
)
as

     DECLARE @oldSequence int
	 DECLARE @newSequence INT
     DECLARE @oModeId Int
-- 升
IF @Sort =1
BEGIN
  Select @oldSequence = DisplaySequence FROM Hishop_PaymentTypes where ModeId =@ModeId

  SELECT @newSequence = DisplaySequence FROM Hishop_PaymentTypes 
  WHERE ModeId = (Select TOP 1 ModeId From Hishop_PaymentTypes Where DisplaySequence <@oldSequence 
    Order by DisplaySequence DESC)

  SELECT @oModeId = (Select TOp 1 ModeId From Hishop_PaymentTypes Where DisplaySequence <@oldSequence
   Order by DisplaySequence DESC)

  IF NOT @newSequence IS NULL
  BEGIN
    Update Hishop_PaymentTypes Set DisplaySequence = @newSequence Where ModeId =@ModeId
  END
  IF NOT @oModeId IS NULL
    BEGIN
  Update Hishop_PaymentTypes Set DisplaySequence = @oldSequence Where modeId =@oModeId
  END
End
-- 降
IF @Sort =0

BEGIN
  Select @oldSequence = DisplaySequence FROM Hishop_PaymentTypes where ModeId =@ModeId

  SELECT @newSequence = DisplaySequence FROM Hishop_PaymentTypes 
  WHERE ModeId = (Select TOp 1 ModeId From Hishop_PaymentTypes Where DisplaySequence >@oldSequence 
    Order by DisplaySequence Asc)
  

  SELECT @oModeId = (Select TOp 1 ModeId From Hishop_PaymentTypes Where DisplaySequence >@oldSequence
  Order by DisplaySequence Asc)
   

  IF NOT @newSequence IS NULL
  BEGIN
    Update Hishop_PaymentTypes Set DisplaySequence = @newSequence Where ModeId =@ModeId
  END
  IF NOT @oModeId IS NULL
    BEGIN
  Update Hishop_PaymentTypes Set DisplaySequence = @oldSequence Where modeId =@oModeId
  END
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[spf_PaymentMode_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[spf_PaymentMode_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spf_PaymentMode_CreateUpdateDelete]
	(
		@ModeId INT = NULL OUTPUT,
		@MerchantCode NVARCHAR(300) = NULL,
		@EmailAddress NVARCHAR(255) = NULL,
		@SecretKey NVARCHAR(4000) = NULL,
		@SecondKey NVARCHAR(4000) = NULL,
		@Password NVARCHAR(4000) = NULL,
		@Partner NVARCHAR(300) = NULL,
		@Name NVARCHAR(100) = null,
		@Description NVARCHAR(4000) = NULL,
		@Gateway NVARCHAR(200) = NULL,
		@DisplaySequence INT = NULL,
		@Charge MONEY = NULL,
		@IsPercent BIT = NULL,
		@Action INT,
		@Status INT OUTPUT
	)
AS
	SET @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN -- 同时删除支付方式的支付货币
	
		SET XACT_ABORT ON
		DECLARE @intErrorCode INT
		
		BEGIN TRAN
		
		DELETE FROM Hishop_PaymentCurrencys WHERE ModeId = @ModeId
		SET @intErrorCode = @@ERROR
		
		IF @intErrorCode = 0
		BEGIN
           DELETE FROM
				Hishop_PaymentTypes
			WHERE
				ModeId = @ModeId
			SET @intErrorCode = @@ERROR 
		END
			
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
			COMMIT TRAN
		END
		ELSE
			ROLLBACK TRAN
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN
           --- 修改显示序号
	    IF  @DisplaySequence IS NULL
           SET @DisplaySequence = (Select Max(DisplaySequence) From Hishop_PaymentTypes) + 1
        ELSE
           UPDATE Hishop_PaymentTypes set DisplaySequence = DisplaySequence + 1 where DisplaySequence >= @DisplaySequence 
		INSERT INTO 
			Hishop_PaymentTypes(MerchantCode, EmailAddress, SecretKey, SecondKey, Password, 
								Partner, [Name], Description, Gateway,  
								 DisplaySequence, Charge, IsPercent)
		VALUES 
			(@MerchantCode, @EmailAddress, @SecretKey, @SecondKey, @Password, 
			@Partner, @Name, @Description, @Gateway,
			@DisplaySequence, @Charge, @IsPercent)
		SELECT @ModeId = @@IDENTITY
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		--判断序号是否为空
       IF  @DisplaySequence IS NUll
          SET @DisplaySequence = (Select Max(DisplaySequence) From Hishop_PaymentTypes) + 1
       Else IF @DisplaySequence != (Select DisplaySequence  From Hishop_PaymentTypes where ModeId=@ModeId)
          UPDATE Hishop_PaymentTypes set DisplaySequence = DisplaySequence + 1 where DisplaySequence >= @DisplaySequence 
      UPDATE 
			 Hishop_PaymentTypes 
		 SET 
			MerchantCode = @MerchantCode,
			EmailAddress = @EmailAddress,
			SecretKey = @SecretKey,
			SecondKey = @SecondKey,
			Password = @Password,
			Partner = @Partner,
			[Name] = @Name,
			Description = @Description,
			Gateway = @Gateway,
			DisplaySequence = @DisplaySequence,
			Charge = @Charge,
			IsPercent = @IsPercent
		WHERE ModeId = @ModeId
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_PaymentMode_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_PaymentMode_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_PaymentMode_CreateUpdateDelete]
	(
		@ModeId INT = NULL OUTPUT,
		@MerchantCode NVARCHAR(300) = NULL,
		@EmailAddress NVARCHAR(255) = NULL,
		@SecretKey NVARCHAR(4000) = NULL,
		@SecondKey NVARCHAR(4000) = NULL,
		@Password NVARCHAR(4000) = NULL,
		@Partner NVARCHAR(300) = NULL,
		@Name NVARCHAR(100) = null,
		@Description NVARCHAR(4000) = NULL,
		@Gateway NVARCHAR(200) = NULL,
		@DisplaySequence INT = NULL,
		@Charge MONEY = NULL,
		@IsPercent BIT = NULL,
		@Action INT,
		@Status INT OUTPUT
	)
AS
	SET @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN -- 同时删除支付方式的支付货币
	
		SET XACT_ABORT ON
		DECLARE @intErrorCode INT
		
		BEGIN TRAN
		
		DELETE FROM Hishop_PaymentCurrencys WHERE ModeId = @ModeId
		SET @intErrorCode = @@ERROR
		
		IF @intErrorCode = 0
        BEGIN
			DELETE FROM
				Hishop_PaymentTypes
			WHERE
				ModeId = @ModeId 
				
			SET @intErrorCode = @@ERROR
		END
			
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
			COMMIT TRAN
		END
		ELSE
			ROLLBACK TRAN
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN
		IF EXISTS(SELECT ModeId FROM Hishop_PaymentTypes WHERE LOWER(Gateway) = LOWER(@Gateway))
		BEGIN
			SET @Status = 3
			SET @ModeId = 0
			RETURN
		END
		
        --- 修改显示序号
	    IF  @DisplaySequence IS NULL
           SET @DisplaySequence = (Select Max(DisplaySequence) From Hishop_PaymentTypes ) + 1
        ELSE
           UPDATE Hishop_PaymentTypes set DisplaySequence = DisplaySequence + 1 where DisplaySequence >= @DisplaySequence 
           
		INSERT INTO 
			Hishop_PaymentTypes(MerchantCode, EmailAddress, SecretKey, SecondKey, Password, 
								Partner, [Name], Description, Gateway, DisplaySequence, Charge, IsPercent)
		VALUES 
			(@MerchantCode, @EmailAddress, @SecretKey, @SecondKey, @Password, 
			@Partner, @Name, @Description, @Gateway, @DisplaySequence, @Charge, @IsPercent)
		
		SELECT @ModeId = @@IDENTITY
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		--判断序号是否为空
       IF  @DisplaySequence IS NUll
          SET @DisplaySequence = (Select Max(DisplaySequence) From Hishop_PaymentTypes) + 1
       Else IF @DisplaySequence != (Select DisplaySequence  From Hishop_PaymentTypes where ModeId=@ModeId)
          UPDATE Hishop_PaymentTypes set DisplaySequence = DisplaySequence + 1 where DisplaySequence >= @DisplaySequence 
       -- 如果@CreatorUserId是空的   则 用户编号不作为修改的条件
       
		UPDATE 
			Hishop_PaymentTypes 
		SET 
			MerchantCode = @MerchantCode,
			EmailAddress = @EmailAddress,
			SecretKey = @SecretKey,
			SecondKey = @SecondKey,
			Password = @Password,
			Partner = @Partner,
			[Name] = @Name,
			Description = @Description,
			--Gateway = @Gateway,修改支付方式时不能修改网关类型
			DisplaySequence = @DisplaySequence,
			Charge = @Charge,
			IsPercent = @IsPercent
		WHERE ModeId = @ModeId
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END' 
END
GO
/****** Object:  View [dbo].[vw_Allregion_Users]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[vw_Allregion_Users]') AND OBJECTPROPERTY(id, N'IsView') = 1)
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vw_Allregion_Users]
AS
SELECT up.RegionId,r.Path, COUNT(up.UserId) AS UserCount
FROM dbo.Hishop_UserProfile up LEFT OUTER JOIN  dbo.Hishop_Regions r ON up.RegionId = r.RegionId
WHERE 
UserRank IS NOT NULL
GROUP BY up.RegionId, r.Path'
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_Regions_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_Regions_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N' CREATE Procedure [dbo].[sp_cs_Regions_CreateUpdateDelete]
(
  @AreaId INT =null,
  @RegionId int =null,
  @RegionName nvarchar(100) =null,
  @DisplaySequence int =null,
  @ParentId int =null,
  @Action INT,
  @Status INT OUTPUT
)
as
/*
	说明：顶级的Path为0，Depth为1，Path的编号之间用逗号分隔
	*/
	DECLARE @newPath VARCHAR(4000), @oldPath VARCHAR(4000)
	DECLARE @newDepth INT, @oldDepth INT
	DECLARE @oldParentRegionId INT
	DECLARE @intErrorCode INT

-- 初始化信息
	SELECT @Status = 99, @intErrorCode = 0
  IF @Action = 2 -- 删除
  BEGIN
    -- 如果区域下有子区域 则不能删除
    IF EXISTS(SELECT  RegionId FROM Hishop_Regions WHERE ParentId = @ParentId)
    BEGIN
			SET @Status = 2
			RETURN
	END

    DELETE FROM Hishop_Regions WHERE RegionId = @RegionId
    IF @@ROWCOUNT = 1
		    SET @Status = 0
    RETURN
  END

 IF @Action = 0 -- 创建
   BEGIN
   IF @ParentId >0 AND EXISTS (SELECT RegionId FROM Hishop_Regions WHERE  RegionId = @ParentId)
    SELECT 
				@newPath = Path + LTRIM(RTRIM(STR(@ParentId))) + '','', 
				@newDepth = Depth + 1 
			FROM 
				Hishop_Regions 
			WHERE RegionId = @ParentId
   -- 没有上级区域
   ELSE
			-- 则将深度设为1，路径设为''0,''
			SELECT @newPath = ''0,'', @newDepth = 1
			
	--如果排序编号在此兄弟节点间存在,则修改分类中兄弟节点的其它的排序编号
		IF EXISTS(SELECT DisplaySequence FROM Hishop_Regions WHERE DisplaySequence = @DisplaySequence AND ParentId = @ParentId) 
		-- 将大于或等于其兄弟节点的排序号加1
			UPDATE Hishop_Regions SET DisplaySequence = DisplaySequence + 1 WHERE ParentId = @ParentId AND DisplaySequence >=@DisplaySequence
			
   INSERT INTO  
		Hishop_Regions (AreaId,RegionName,DisplaySequence, ParentId ,Depth, Path)
   VALUES 
	   (@AreaId,@RegionName, @DisplaySequence,@ParentId ,@newDepth, @newPath)
    
  	IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
 END

 IF @Action = 1 --修改
  BEGIN
   DECLARE @parentRegoinChanged BIT
-- 获取修改前的上级区域，路径，深度
	SELECT 
			@parentRegoinChanged = 0, @oldParentRegionId = ParentId, 
			@newPath = Path, @oldPath = Path, @newDepth = Depth, @oldDepth = Depth 
		FROM 
			Hishop_Regions
		WHERE 
			RegionId = @RegionId
    -- 检查是否修改上级区域
		IF @ParentId != @oldParentRegionId
        BEGIN
        set @parentRegoinChanged =1
        -- 检查是否指定了上级区域且上级区域存在
         IF @ParentId >0 AND EXISTS (SELECT RegionId FROM Hishop_Regions WHERE  RegionId = @ParentId)
          -- 根据新上级区域获取路径和深度
          SELECT 
					@newPath = Path + LTRIM(RTRIM(STR(@ParentId))) + '','', 
					@newDepth = Depth + 1 
				FROM 
					Hishop_Regions 
				WHERE RegionId = @ParentId
          -- 没有上级区域
         ELSE
          -- 则将深度设为1，路径设为''0,''
			SELECT @newPath = ''0,'', @newDepth = 1
         END

        SET XACT_Abort ON
		BEGIN TRAN
		
		--如果排序编号在此兄弟节点间存在,则修改分类中兄弟节点的其它的排序编号
		IF EXISTS(SELECT DisplaySequence FROM Hishop_Regions WHERE DisplaySequence = @DisplaySequence AND ParentId = @ParentId) 
		-- 将大于或等于其兄弟节点的排序号加1
			UPDATE Hishop_Regions SET DisplaySequence = DisplaySequence + 1 WHERE ParentId = @ParentId AND DisplaySequence >=@DisplaySequence

        -- 修改区域信息
        UPDATE Hishop_Regions 
        SET 
           AreaId =@AreaId,
           RegionName = @RegionName,
           DisplaySequence = @DisplaySequence,
           ParentId = @ParentId,
           Depth = @newDepth,
		   Path = @newPath
        Where RegionId = @RegionId
        SET @intErrorCode = @intErrorCode + @@ERROR

        IF @intErrorCode = 0 AND @parentRegoinChanged = 1
        BEGIN
          -- 修改子区域的深度和路径
            UPDATE 
				Hishop_Regions 
			SET
				Path = REPLACE(Path, @oldPath, @newPath),
				Depth = Depth + (@newDepth - @oldDepth)
			WHERE Path LIKE @oldPath + ''%''
			
			SET @intErrorCode = @intErrorCode + @@ERROR
       END

    	IF @intErrorCode = 0
		BEGIN
			COMMIT TRAN
			SET @Status = 0
		END
		ELSE
			ROLLBACK TRAN
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_Regions_Sequence]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_Regions_Sequence]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_Regions_Sequence]
	(
  @Sort INT , -- 是升 还是降 1 表示升 2表示降
  @RegionId INT
)
As 
     -- 当前要修改的序号
	 DECLARE @oldSequence INT
	 -- 要修改成的序号
	 DECLARE @newSequence INT
	 -- 和当前对换的编号
	 DECLARE @newRegionId INT
     
     DECLARE @Depth INT
 --升
 IF @Sort =1
    
 BEGIN
	
	 SELECT @oldSequence = DisplaySequence, @Depth = Depth FROM [Hishop_Regions]
     WHERE RegionId = @RegionId
 
     SELECT @newSequence = DisplaySequence FROM [Hishop_Regions]
     WHERE RegionId =
		(SELECT TOP 1 RegionId FROM [Hishop_Regions]
		WHERE DisplaySequence < @oldSequence AND Depth = @Depth 
     Order by DisplaySequence DESC) 

     SELECT @newRegionId = (SELECT TOP 1 RegionId FROM [Hishop_Regions]
     WHERE DisplaySequence < @oldSequence AND Depth = @Depth
     ORDER BY DisplaySequence DESC)
    IF @newRegionId IS NOT NULL
     BEGIN
		  Update [Hishop_Regions] SET DisplaySequence =@newSequence 
		  WHERE RegionId = @RegionId
     END
    IF @newRegionId IS NOT NULL
     BEGIN
		  Update [Hishop_Regions] SET DisplaySequence = @oldSequence
		  WHERE RegionId = @newRegionId 
     END
  END 
 --降低
 IF @Sort = 0
 BEGIN
	SELECT @oldSequence = DisplaySequence,@Depth = Depth FROM [Hishop_Regions]
	WHERE RegionId =@RegionId
	 
	SELECT @newSequence = DisplaySequence FROM [Hishop_Regions]
	WHERE RegionId =
		 (SELECT TOP 1 RegionId FROM [Hishop_Regions]
		 WHERE DisplaySequence>@oldSequence  AND Depth = @Depth
		   Order by DisplaySequence ASC)
     
	 
	SELECT @newRegionId = (SELECT TOP 1 RegionId FROM [Hishop_Regions]
	WHERE DisplaySequence > @oldSequence AND Depth = @Depth
	 Order by DisplaySequence ASC)
    
    IF @newSequence IS NOT NULL
     BEGIN
		  UPDATE [Hishop_Regions] SET DisplaySequence = @newSequence 
		  WHERE RegionId = @RegionId 
     END
    IF @newRegionId IS NOT NULL
     BEGIN
		  UPDATE [Hishop_Regions] Set DisplaySequence = @oldSequence
		  WHERE RegionId =@newRegionId 
     END
 END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_OrderGiftItem_Add]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_OrderGiftItem_Add]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[sp_OrderGiftItem_Add]
(
	@OrderId	nvarchar(50) =null,
	@GiftId	int	= null,
	@GiftName	nvarchar(100)=null,
	@CostPrice	money	=null,
	@AdjustedPrice	money	=null
)
as 
BEGIN TRAN
 INSERT INTO Hishop_OrderGifts
  (OrderId,GiftId,GiftName,CostPrice,AdjustedPrice)
 VALUES(@OrderId,@GiftId,@GiftName,@CostPrice,@AdjustedPrice)
COMMIT' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cd_CreateOrder]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cd_CreateOrder]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[sp_cd_CreateOrder]
(
	-- 基本信息
    @OrderId nvarchar(50),
	@OrderDate	datetime,	
	@UserId	int,
    @UserName nvarchar(50),
    @EmailAddress	nvarchar(255) = null,
    @Remark Nvarchar(4000) =null,
	@AdjustedDiscount money,
	@ActivityStatus int,
	@IsPOD bit,
	-- 配送信息
	@ShippingRegion Nvarchar(300) = null,
	@Address Nvarchar(300) = null,
	@ZipCode Nvarchar(20) = null,
	@ShipTo Nvarchar(50) = null,
	@TelPhone Nvarchar(50) = null,
	@CellPhone Nvarchar(50) = null,
	@ShippingModeId int = null,
	@ModeName Nvarchar(50) = null,
	@RegionId int = null,
	@Freight money = null,
	@AdjustedFreight money = null,
	@ShipOrderNumber Nvarchar(50) = null,	
    @Weight int = null,
    @ShippingStatus int = null,
    -- 支付信息
    @PaymentGateway Nvarchar(50) = null,
    @PaymentType Nvarchar(100) = null,	
    @CurrencyCode Nvarchar(20) = null,
    @CurrencyName Nvarchar(20) = null,
    @PayCharge money = null,
    @AdjustedPayCharge money = null,
    @RefundStatus int,
    @PaymentStatus int,
    -- 统计字段
    @OrderTotal money = null,
    @OrderCostPrice money = null,
    @OrderProfit money = null,
    @OptionPrice money = null,
    @Amount money = null,    
    -- 满额免费用促销活动
    @ActivityName Nvarchar(100)= null,
    @FeeFreeAmount money= null,
    @EightFree bit = 0,
    @ProcedureFeeFree bit = 0,
    @OrderOptionFree bit = 0,
    --满额打折促销活动
    @DiscountName nvarchar(100) = null,
    @DiscountAmount money = null,
    @DiscountValue money = null,
    @DiscountValueType int = null,
    -- 优惠券信息
    @CouponName nvarchar(100) = null,
	@CouponCode nvarchar(50) = null,
	@CouponAmount money = null,    
	@CouponValue money = null
)
as 
  IF EXISTS (SELECT OrderId  FROM Hishop_Orders WHERE OrderId = @OrderId)
    Return
  ELSE
  INSERT INTO Hishop_Orders
   (OrderId, OrderDate, UserId, Username, EmailAddress, Remark, AdjustedDiscount, ActivityStatus, IsPOD,
   ShippingRegion, Address, ZipCode, ShipTo, TelPhone, CellPhone, ShippingModeId, ModeName, RegionId, Freight, AdjustedFreight, ShipOrderNumber, Weight, ShippingStatus,
   PaymentGateway,PaymentType,CurrencyCode, CurrencyName, PayCharge, AdjustedPayCharge, RefundStatus, PaymentStatus,
   OrderTotal, OrderCostPrice, OrderProfit, OptionPrice, Amount, 
   ActivityName, FeeFreeAmount, EightFree, ProcedureFeeFree, OrderOptionFree,
   DiscountName, DiscountAmount, DiscountValue, DiscountValueType, 
   CouponName, CouponCode, CouponAmount, CouponValue
  )
  VALUES 
  (@OrderId, @OrderDate, @UserId, @Username, @EmailAddress, @Remark, @AdjustedDiscount, @ActivityStatus, @IsPOD,
   @ShippingRegion, @Address, @ZipCode, @ShipTo, @TelPhone, @CellPhone, @ShippingModeId, @ModeName, @RegionId, @Freight, @AdjustedFreight, @ShipOrderNumber, @Weight, @ShippingStatus,
   @PaymentGateway,@PaymentType,@CurrencyCode, @CurrencyName, @PayCharge, @AdjustedPayCharge, @RefundStatus, @PaymentStatus,
   @OrderTotal, @OrderCostPrice, @OrderProfit, @OptionPrice, @Amount, 
   @ActivityName, @FeeFreeAmount, @EightFree, @ProcedureFeeFree, @OrderOptionFree, 
   @DiscountName, @DiscountAmount, @DiscountValue, @DiscountValueType, 
   @CouponName, @CouponCode, @CouponAmount, @CouponValue
   )' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_Orders_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_Orders_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_Orders_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@TotalOrders int = 0 output
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex-1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForOrders
	(
		IndexId int IDENTITY (1, 1) NOT NULL,
		OrderId nvarchar(50),
		PublishDate datetime,
		ActionDate Datetime,
	)	

	INSERT INTO #PageIndexForOrders(OrderId,PublishDate,ActionDate)
	Exec sp_executesql @sqlPopulate

	SET @TotalOrders = @@rowcount
	
	SELECT o.*,o.OrderTotal AS OrderPrice,
	    (select count(LeaveId) from Hishop_OrderLeaveWords where OrderId = O.OrderId and IsAdminVisited=0 ) as NoVisitNum,
	    (select count(LeaveId) from Hishop_OrderLeaveWords where OrderId = O.OrderId  ) as VisitNum,
		(select f.Username from vw_Users_FullUser f 
			where f.hi_userid=(select f1.ParentUserId from vw_Users_FullUser f1 where f1.hi_userid=o.UserId)) as ParentUserName,
		(select ParentUserId from vw_Users_FullUser where hi_userid=o.UserId) as ParentUserId
	FROM Hishop_Orders o, #PageIndexForOrders
	WHERE 
		o.OrderId = #PageIndexForOrders.OrderId AND
		#PageIndexForOrders.IndexId > @PageLowerBound AND
		#PageIndexForOrders.IndexId < @PageUpperBound 
	ORDER BY #PageIndexForOrders.IndexId


    -- ����
	SELECT Count(orderId) as AllOrderNmb FROM Hishop_Orders 
	-- δ�����
    SELECT Count(orderId) as NotPayOrderNmb FROM Hishop_Orders where PaymentStatus=0 and ShippingStatus=0
    -- �Ѹ����
    SELECT Count(orderId) as YetPayOrderNmb FROM Hishop_Orders where PaymentStatus=1 and ShippingStatus=0 and ActivityStatus = 0
    -- ����ж���
    SELECT Count(orderId) as SendingGoodsOrderNmb FROM Hishop_Orders where ShippingStatus=2
    -- �ѷ�������
    SELECT Count(orderId) as SendedGoodsOrderNmb FROM Hishop_Orders where ShippingStatus=1 and ActivityStatus = 0
    -- ����ɶ���
    SELECT Count(orderId) as TradeFinishedOrderNmb FROM Hishop_Orders where ActivityStatus=2
	-- �����˿��
    SELECT Count(orderId) as RequestedOrderNmb FROM Hishop_Orders where RefundStatus=1
    -- ���˿��
    SELECT Count(orderId) as RefundOrderNmb FROM Hishop_Orders where RefundStatus=2
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cs_Currency_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cs_Currency_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cs_Currency_CreateUpdateDelete]
(
    @Code NVARCHAR(20) = NULL,
    @Name NVARCHAR(20) = NULL,
    @Symbol NVARCHAR(20) = NULL,
    @ExchangeRate MONEY = NULL,
    @Action INT,
    @Status INT OUTPUT
)
AS
	DECLARE @DuplicateCurrency INT
	
	SET @Status = 99

	IF @Action = 2 -- 删除
	BEGIN
	
		DELETE FROM Hishop_Currencys WHERE Code=@Code
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 0 --创建
	BEGIN
		SELECT @DuplicateCurrency = COUNT(*) FROM Hishop_Currencys WHERE  Code = @Code
		IF @DuplicateCurrency = 0
		BEGIN
			INSERT INTO Hishop_Currencys (Code,[Name],Symbol,ExchangeRate) VALUES (@Code,@Name,@Symbol,@ExchangeRate)
	
			SELECT @Code = @@IDENTITY 
	
			IF @@ROWCOUNT = 1
				SET @Status = 0
		END
		ELSE
			SET @Status = 1
	
		RETURN
	END

	IF @Action = 1 --修改
	BEGIN
		UPDATE
			Hishop_Currencys
		SET 
			[Name]=@Name,Symbol=@Symbol,ExchangeRate=@ExchangeRate 
		WHERE 
			Code=@code

		IF @@ROWCOUNT = 1

		SET @Status = 0
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_ArticleCategory_SwapDisplaySequence]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_ArticleCategory_SwapDisplaySequence]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_ArticleCategory_SwapDisplaySequence]
	(
		@CategoryId INT,
		@CategoryId2 INT
	)
AS
	
	DECLARE @DisplaySequence2 INT
	DECLARE @DisplaySequence INT
	
	SELECT @DisplaySequence = DisplaySequence FROM Hishop_ArticleCategories WHERE CategoryId = @CategoryId
	SELECT @DisplaySequence2 = DisplaySequence FROM Hishop_ArticleCategories WHERE CategoryId = @CategoryId2
	
	IF @DisplaySequence IS NULL OR @DisplaySequence2 IS NULL
		RETURN
	
	UPDATE Hishop_ArticleCategories SET DisplaySequence = @DisplaySequence2 WHERE CategoryId = @CategoryId
	UPDATE Hishop_ArticleCategories SET DisplaySequence = @DisplaySequence WHERE CategoryId = @CategoryId2' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_ArticleCategory_MainCategory]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_ArticleCategory_MainCategory]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_ArticleCategory_MainCategory]

AS
SELECT * From Hishop_ArticleCategories ORDER BY [DisplaySequence]' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ArticleCategory_Select]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ArticleCategory_Select]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ArticleCategory_Select]
	@CategoryId INT = NULL,
	@Action     INT
AS
if      @Action = 0
	SELECT * FROM Hishop_ArticleCategories ORDER BY [DisplaySequence]
else if @Action = 1
	SELECT * From Hishop_ArticleCategories ORDER BY [DisplaySequence]
else if @Action = 2
	SELECT * From Hishop_ArticleCategories WHERE CategoryId=@CategoryId ORDER BY [DisplaySequence]' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_ArticleCategory_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_ArticleCategory_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_ArticleCategory_Get]
	@CategoryId int
AS
SELECT * From Hishop_ArticleCategories WHERE CategoryId=@CategoryId ORDER BY [DisplaySequence]' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_Product_Create]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_Product_Create]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_Product_Create]
	(
		@CategoryId INT,
		@TypeId INT = NULL,	
		@BrandId INT = NULL,
		@SKU NVARCHAR(50) = NULL,
		@SupplierId INT = NULL,
		@SupplierName NVARCHAR(50) = NULL,
		@ProductName NVARCHAR(200),
		@ShortDescription NVARCHAR(2000) = NULL,
		@Unit NVARCHAR(10) = NULL,
		@Weight INT = NULL,
		@Description NTEXT = NULL,
		@Title NVARCHAR(100) = NULL,
		@Meta_Description NVARCHAR(1000) = NULL,
		@Meta_Keywords NVARCHAR(1000) = NULL,
		@ThumbnailsUrl NVARCHAR(255) = NULL,
		@InFocusImageUrl NVARCHAR(255) = NULL,
		@Recommended BIT,
		@Latest BIT,
		@Hotsale BIT,
		@SpecialOffer BIT,
		@CostPrice MONEY = NULL,
		@MarketPrice MONEY = NULL,
		@Upselling BIT,
		@SalePrice MONEY,
		@Stock INT = NULL,
		@QuantityLimit INT = NULL,
		@MinQuantity INT,		
		@AddedDate DATETIME,
		@VistiCounts INT,
		@DisplaySequence INT,
		@ProductId INT OUTPUT
	)
AS

SET @ProductId = 0
--货号不能重复
IF EXISTS(SELECT ProductId FROM Hishop_Products WHERE SKU = @SKU)
	RETURN
--如果商品显示顺序存在，则所有这个商品后台的顺序加一
IF EXISTS(SELECT ProductId FROM Hishop_Products WHERE DisplaySequence = @DisplaySequence)
	UPDATE Hishop_Products SET DisplaySequence = DisplaySequence + 1 WHERE DisplaySequence >= DisplaySequence
INSERT INTO Hishop_Products 
	(CategoryId, TypeId, BrandId, SKU, SupplierId, ProductName, ShortDescription, Unit, Weight, Description, Title, Meta_Description, Meta_Keywords, ThumbnailsUrl, InFocusImageUrl, Recommended, Latest,
		Hotsale, SpecialOffer, CostPrice, MarketPrice, Upselling, SalePrice, Stock, QuantityLimit, MinQuantity, AddedDate,VistiCounts, DisplaySequence) 
Values
	(@CategoryId, @TypeId, @BrandId, @SKU, @SupplierId, @ProductName, @ShortDescription, @Unit, @Weight, @Description, @Title, @Meta_Description, @Meta_Keywords, @ThumbnailsUrl, @InFocusImageUrl, @Recommended,
		 @Latest, @Hotsale, @SpecialOffer, @CostPrice, @MarketPrice, @Upselling, @SalePrice, @Stock, @QuantityLimit, @MinQuantity, @AddedDate,  @VistiCounts, @DisplaySequence)
SET @ProductId = @@IDENTITY;' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_Product_Update]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_Product_Update]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_Product_Update]
	(
		@CategoryId INT,
		@TypeId INT = NULL,	
		@BrandId INT = NULL,
		@SKU NVARCHAR(50) = NULL,
		@SupplierId INT = NULL,
		@SupplierName NVARCHAR(50) = NULL,
		@ProductName NVARCHAR(200),
		@ShortDescription NVARCHAR(2000) = NULL,
		@Unit NVARCHAR(10) = NULL,
		@Weight INT = NULL,
		@Description NTEXT = NULL,
		@Title NVARCHAR(100) = NULL,
		@Meta_Description NVARCHAR(1000) = NULL,
		@Meta_Keywords NVARCHAR(1000) = NULL,
		@ThumbnailsUrl NVARCHAR(255) = NULL,
		@InFocusImageUrl NVARCHAR(255) = NULL,
		@Recommended BIT,
		@Latest BIT,
		@Hotsale BIT,
		@SpecialOffer BIT,
		@CostPrice MONEY = NULL,
		@MarketPrice MONEY = NULL,
		@Upselling BIT,
		@SalePrice MONEY,
		@Stock INT = NULL,
		@QuantityLimit INT = NULL,
		@MinQuantity INT,		
		@AddedDate DATETIME,
		@VistiCounts INT,
		@DisplaySequence INT,
		@ProductId INT
	)
AS

--货号修改后不能重复
IF (SELECT SKU FROM Hishop_Products WHERE ProductId = @ProductId) != @SKU AND EXISTS(SELECT ProductId FROM Hishop_Products WHERE SKU = @SKU) 
	RETURN
--如果商品显示顺序存在，则所有这个商品后台的顺序加一
IF (SELECT DisplaySequence FROM Hishop_Products WHERE ProductId = @ProductId) != @DisplaySequence AND EXISTS(SELECT ProductId FROM Hishop_Products WHERE DisplaySequence = @DisplaySequence)
	UPDATE Hishop_Products SET DisplaySequence = DisplaySequence + 1 WHERE DisplaySequence >= DisplaySequence
	
UPDATE Hishop_Products SET
	CategoryId = @CategoryId, TypeId = @TypeId, BrandId = @BrandId, SKU = @SKU, SupplierId = @SupplierId, ProductName = @ProductName, ShortDescription = @ShortDescription, Unit = @Unit,
	Weight = @Weight, Description = @Description, Title = @Title, Meta_Description = @Meta_Description, Meta_Keywords = @Meta_Keywords, ThumbnailsUrl = @ThumbnailsUrl, InFocusImageUrl = @InFocusImageUrl,
	Recommended = @Recommended, Latest = @Latest, Hotsale = @Hotsale, SpecialOffer = @SpecialOffer, CostPrice = @CostPrice, MarketPrice = @MarketPrice, Upselling = @Upselling, SalePrice = @SalePrice,
	Stock = @Stock, QuantityLimit = @QuantityLimit, MinQuantity = @MinQuantity, AddedDate = @AddedDate, DisplaySequence = @DisplaySequence WHERE ProductId = @ProductId' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_PrivilegeInRoles_AddDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_PrivilegeInRoles_AddDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_PrivilegeInRoles_AddDelete]
	@RoleId uniqueidentifier, 
	@ResourceId INT,
	@OperationId INT,
	@Action INT
AS	
	IF @Action = 2 -- 删除
	BEGIN	
		DELETE FROM 
			Hishop_PrivilegeInRoles 
		WHERE 
			RoleId=@RoleId AND ResourceId=@ResourceId AND OperationId=@OperationId
		
		RETURN
	END
	
	IF @Action = 0 -- 创建
	BEGIN
		IF EXISTS(SELECT * FROM Hishop_PrivilegeInRoles WHERE RoleId=@RoleId AND ResourceId=@ResourceId AND OperationId=@OperationId)
			RETURN
		
		ELSE
		
			INSERT INTO Hishop_PrivilegeInRoles(RoleId,ResourceId,OperationId)
			VALUES(@RoleId,@ResourceId,@OperationId)
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_Votes_Create]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_Votes_Create]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_Votes_Create]
	(
		@VoteName NVARCHAR(100),
		@IsBackup BIT,
		@MaxCheck INT,
		@VoteId int OUTPUT
	)
AS

IF @IsBackup = 1
	BEGIN
		UPDATE Hishop_Votes SET IsBackup = 0
	END

INSERT INTO Hishop_Votes (VoteName, IsBackup, MaxCheck)
 VALUES (@VoteName, @IsBackup, @MaxCheck)
SET @VoteId = @@IDENTITY' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_Vote_IsBackup]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_Vote_IsBackup]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Procedure [dbo].[sp_cg_Vote_IsBackup]
(
  @VoteId INT
)
AS
BEGIN
  Update Hishop_Votes 
   Set IsBackup = (~IsBackup)
    Where VoteId =@VoteId
    
    Update Hishop_Votes 
   Set IsBackup = (~IsBackup)
    Where VoteId <>@VoteId AND IsBackup = 1
 END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spb_PromoteProducts_CreateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[spb_PromoteProducts_CreateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spb_PromoteProducts_CreateDelete]
	@ActivityId INT, 
	@ProductId  INT,
	@Type		INT = 0,
	@Action		INT,
    @Status INT OUTPUT
AS
	-- 初始化信息
	SELECT @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN
		DELETE FROM Hishop_PromoteSales_Products WHERE ActivityId=@ActivityId AND ProductId=@ProductId
		IF @@ROWCOUNT   = 1
		    SET @Status = 0
		RETURN
	END
	
	IF @Action = 0 -- 创建
    BEGIN
		INSERT Hishop_PromoteSales_Products(ActivityId,ProductId,Type)VALUES(@ActivityId,@ProductId,@Type)
		IF @@ROWCOUNT   = 1
			SET @Status = 0
		RETURN
    END' 
END
GO
/****** Object:  StoredProcedure [dbo].[spb_RelatedProduct_Add]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[spb_RelatedProduct_Add]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[spb_RelatedProduct_Add] 
	(
		@ProductId INT,
		@RelatedProductId INT
	)
AS
	-- 检查是否已经添加了指定的相关商品
	IF EXISTS(SELECT * FROM Hishop_RelatedProducts WHERE ProductId = @ProductId AND RelatedProductId = @RelatedProductId)
		RETURN
		
	-- 检查商品是否存在
	IF NOT EXISTS(SELECT ProductName FROM Hishop_Products WHERE ProductId = @ProductId)
		RETURN
		
	-- 检查相关商品是否存在
	IF NOT EXISTS(SELECT ProductName FROM Hishop_Products WHERE ProductId = @RelatedProductId)
		RETURN
		
	INSERT INTO 
		Hishop_RelatedProducts (ProductId, RelatedProductId)
	VALUES 
		(@ProductId, @RelatedProductId)' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_system_UserIsOnline]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_system_UserIsOnline]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_system_UserIsOnline]
(
	@UserId int,
	@LastAction nvarchar(1024)
)
AS
	UPDATE Hishop_Users SET LastActivity = getdate(),LastAction = @LastAction WHERE UserId = @UserId' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_User_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_User_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  procedure [dbo].[sp_User_CreateUpdateDelete] 
(
	@hi_UserId int out,
	@UserId uniqueidentifier = null,
	@UserName   nvarchar (64) = '''',
	@UserAccountStatus  smallint = 1,
	@IsAnonymous   smallint = 0,
	@IsIgnored     bit = 0,
	@AppUserToken       varchar (128) = '''',
	@ForceLogin   bit   = 0,
	@EnableDisplayInMemberList  smallint  = 1,
	@EnablePrivateMessages  smallint  = 1,
	@EnableOnlineStatus smallint  = 1,
	@EnableEmail smallint  = 1,
	@EnableHtmlEmail   smallint  = 1,
	@Action    int,
	@EnableTradePassword BIT,
	@RealName NVARCHAR(50),
	@RegionId INT,
	@TradePassword NVARCHAR(128) = NULL,
	@TradePasswordSalt NVARCHAR(128) = NULL,
	@TradePasswordFormat INT = 0,
	@Address NVARCHAR(300) = NULL,
    @QQ NVARCHAR(20) = NULL,
    @MSN NVARCHAR(20) = NULL,
    @TelPhone NVARCHAR(50) = NULL,
    @CellPhone NVARCHAR(50) = NULL,
    @BirthDate datetime = NULL,
    @Gender int = NULL,
    @UserRank int = NULL,
    @Agent_Expires datetime = NULL,
	@Agent_IsUrlBindApproved bit = NULL,
	@Agent_SiteUrl nvarchar(255) = NULL,
	@Agent_LogoUrl nvarchar (255)=  NULL,
	@Agent_Footer ntext = NULL,
	@Agent_SiteName nvarchar(50) =  NULL,
	@Agent_SiteDescription nvarchar(60) =  NULL,
	@Agent_Theme nvarchar(50) =  NULL,
	@ParentUserId INT = NULL,
	@ReferralUserId INT = NULL
)
AS
/*
This sproc returns an int that indicates the CreateUserStatus enum value:
	UnknownFailure = 0
	Created = 1
	DuplicateUsername = 2
	DuplicateEmailAddress = 3
	InvalidFirstCharacter = 4
	DisallowedUsername = 5
	Updated = 6
	Deleted = 7
	InvalidQuestionAnswer = 8
	InvalidPassword = 9
*/

-- first, we need to check if the username is a dup

-- Are we creating a user?
IF @Action = 0
BEGIN
	IF (@IsAnonymous = 1)
	BEGIN
		SELECT @hi_UserId = hi_UserId FROM vw_Users_FullUser WHERE UserName = @UserName AND IsAnonymous = 1
		
		-- Check if the anonymous user already exists
		IF @hi_UserId IS NOT NULL
		Begin
			SELECT 1
			RETURN
		End
		
	END
	ELSE
	BEGIN
		Declare @ApplicationName nvarchar(256)
		Select @ApplicationName = ApplicationName FROM Hishop_SiteSettings

		INSERT INTO [Hishop_Users]([MembershipId], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction])
		VALUES(@UserId, @ForceLogin,@UserAccountStatus, @AppUserToken, getdate(), '''')

		Select @hi_UserId = @@Identity

		INSERT INTO Hishop_UserProfile ( [UserId], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableEmail], [EnableHtmlEmail], [IsIgnored], [MembershipId], [EnableTradePassword], [RealName], [RegionId], [TradePassword], [TradePasswordSalt], [Address], [QQ], [MSN],[TelPhone], [CellPhone], [TradePasswordFormat], [BirthDate], [Gender], [UserRank], [Agent_Expires], [Agent_IsUrlBindApproved], [Agent_SiteUrl], [Agent_LogoUrl], [Agent_Footer], [Agent_SiteName], [Agent_SiteDescription], [Agent_Theme], [ParentUserId], [ReferralUserId])
		Select @hi_UserId,   @EnableDisplayInMemberList, @EnablePrivateMessages,   @EnableOnlineStatus,  @EnableEmail, @EnableHtmlEmail, @IsIgnored,  @UserId, @EnableTradePassword, @RealName, @RegionId, @TradePassword, @TradePasswordSalt, @Address, @QQ, @MSN, @TelPhone, @CellPhone, @TradePasswordFormat, @BirthDate, @Gender, @UserRank, @Agent_Expires, @Agent_IsUrlBindApproved, @Agent_SiteUrl, @Agent_LogoUrl, @Agent_Footer, @Agent_SiteName, @Agent_SiteDescription, @Agent_Theme, @ParentUserId, @ReferralUserId
		FROM Hishop_SiteSettings where ApplicationName = @ApplicationName
		
		Select 1
		RETURN
	END
END
ELSE
BEGIN

	UPDATE
		Hishop_UserProfile
	SET
		EnableDisplayInMemberList = @EnableDisplayInMemberList,
		EnablePrivateMessages = @EnablePrivateMessages,
		EnableOnlineStatus = @EnableOnlineStatus,
		EnableEmail = @EnableEmail,
		EnableHtmlEmail = @EnableHtmlEmail,
		IsIgnored = @IsIgnored,
		EnableTradePassword = @EnableTradePassword,
		RealName = @RealName,
		RegionId = @RegionId,
		Address = @Address,
        QQ = @QQ,
        MSN = @MSN,
        TelPhone = @TelPhone,
        CellPhone = @CellPhone,
        BirthDate = @BirthDate,
        Gender = @Gender,
        UserRank = @UserRank,
        Agent_Expires = @Agent_Expires,
		Agent_IsUrlBindApproved = @Agent_IsUrlBindApproved,
		Agent_SiteUrl = @Agent_SiteUrl,
		Agent_LogoUrl = @Agent_LogoUrl,
		Agent_Footer = @Agent_Footer,
		Agent_SiteName = @Agent_SiteName,
		Agent_SiteDescription = @Agent_SiteDescription,
		Agent_Theme = @Agent_Theme
	WHERE
		UserId = @hi_UserId
	

	-- Update the user''s anonymous settings passed in, as well.
	UPDATE aspnet_Users
	SET IsAnonymous = @IsAnonymous
	WHERE UserId = @UserId

	UPDATE
		Hishop_Users
	SET
		AppUserToken = @AppUserToken,
		UserAccountStatus = @UserAccountStatus,
		ForceLogin = @ForceLogin
	WHERE
		 MembershipId = @UserId

	SELECT 6
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_User_ToggleSettings]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_User_ToggleSettings]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[sp_User_ToggleSettings]
(
	@UserId int,
	@UserAccountStatus int,
	@ForceLogin bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE	@CurrentUserAccountStatus	int
	SELECT	@CurrentUserAccountStatus = UserAccountStatus
	FROM	Hishop_Users
	WHERE	UserId = @UserId

	UPDATE 
		Hishop_Users
	SET
		UserAccountStatus = @UserAccountStatus,
		ForceLogin = @ForceLogin
	WHERE
		UserId = @UserId

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_User_SetDealPassword]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_User_SetDealPassword]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_User_SetDealPassword]
    @Username		NVARCHAR(256),
    @NewPassword    NVARCHAR(128),
    @TradePasswordFormat INT,
    @TradePasswordSalt NVARCHAR(128),
	@Success BIT OUT
AS
BEGIN
	DECLARE @UserId INT
	DECLARE @MembershipId uniqueidentifier
	
	SELECT @MembershipId = UserId FROM aspnet_Users WHERE LOWER(Username) = LOWER(@Username)
	SELECT @UserId = UserId FROM Hishop_Users WHERE MembershipId = @MembershipId
	
    UPDATE Hishop_UserProfile SET 
					TradePassword = @NewPassword,
					TradePasswordFormat = @TradePasswordFormat,
					TradePasswordSalt = @TradePasswordSalt
		WHERE UserId = @UserId
    
    SET @Success = @@ROWCOUNT
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_User_ValidTradePassword]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_User_ValidTradePassword]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_User_ValidTradePassword]
    @Username		NVARCHAR(256),
    @TradePassword	NVARCHAR(128),
	@IsValid		BIT OUTPUT
AS
BEGIN
	DECLARE @UserId INT
	DECLARE @MembershipId uniqueidentifier
	
	SELECT @MembershipId = UserId FROM aspnet_Users WHERE LOWER(Username) = LOWER(@Username)
	SELECT @UserId = UserId FROM Hishop_Users WHERE MembershipId = @MembershipId
	
    IF EXISTS(SELECT * FROM Hishop_UserProfile WHERE UserId = @UserId AND TradePassword = @TradePassword)
		SET @IsValid = 1
	ELSE
		SET @IsValid = 0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_InsertForum]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_InsertForum]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_InsertForum]

AS
	
	DECLARE @intErrorCode INT
	SET @intErrorCode = 0
	
	BEGIN TRAN
	
	--插入DZ论坛整合
	INSERT INTO Hishop_IntegrationSettings  VALUES(''DiscuzNT-2.5'',''<?xml version="1.0"?>
<DiscuzForumInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ForumName></ForumName>
  <ForumURL></ForumURL>
  <Dbconnectstring></Dbconnectstring>
  <DataSource></DataSource>
  <InitialCatalog></InitialCatalog>
  <UserID></UserID>
  <Password></Password>
  <Tableprefix>dnt_</Tableprefix>
  <Passwordmode>0</Passwordmode>
  <Passwordkey></Passwordkey>
  <CookieDomain></CookieDomain>
  <IsOff>false</IsOff>
</DiscuzForumInfo>'',0,0,''IntegrationDZSetting.aspx?IntegrationForumId={0}'')
	SET @intErrorCode = @@ERROR
	
	--IF @intErrorCode = 0
	--BEGIN
		--UPDATE Hishop_IntegrationSettings SET IsOff = 1 WHERE IntegrationForumId = @IntegrationForumId
		--SET @intErrorCode = @@ERROR
	--END
	
	IF @intErrorCode = 0
		COMMIT TRAN
	ELSE
		ROLLBACK TRAN' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_SetIsOffForum]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_SetIsOffForum]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_SetIsOffForum]
	(
		@IntegrationForumId INT
	)
AS
	
	DECLARE @intErrorCode INT
	SET @intErrorCode = 0
	
	BEGIN TRAN
	
	UPDATE Hishop_IntegrationSettings SET IsOff = 0 WHERE IntegrationForumId <> @IntegrationForumId
	SET @intErrorCode = @@ERROR
	
	IF @intErrorCode = 0
	BEGIN
		UPDATE Hishop_IntegrationSettings SET IsOff = 1 WHERE IntegrationForumId = @IntegrationForumId
		SET @intErrorCode = @@ERROR
	END
	
	IF @intErrorCode = 0
		COMMIT TRAN
	ELSE
		ROLLBACK TRAN' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cc_Attribute_SwapDisplaySequence]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cc_Attribute_SwapDisplaySequence]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cc_Attribute_SwapDisplaySequence]
	(
		@AttributeId INT,
		@ReplaceAttributeId INT
	)
AS
	
	DECLARE @DisplaySequence2 INT
	DECLARE @DisplaySequence INT
	
	SELECT @DisplaySequence = DisplaySequence FROM Hishop_Attributes WHERE AttributeId = @AttributeId
	SELECT @DisplaySequence2 = DisplaySequence FROM Hishop_Attributes WHERE AttributeId = @ReplaceAttributeId
	
	IF @DisplaySequence IS NULL OR @DisplaySequence2 IS NULL
		RETURN
	
	UPDATE Hishop_Attributes SET DisplaySequence = @DisplaySequence2 WHERE AttributeId = @AttributeId
	UPDATE Hishop_Attributes SET DisplaySequence = @DisplaySequence WHERE AttributeId = @ReplaceAttributeId' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ManageLogs_Add]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ManageLogs_Add]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ManageLogs_Add]
(	
	@ResourceName nvarchar(200),
	@OperationName nvarchar(200),
	@PageUrl nvarchar(255),
	@AddedTime datetime,
	@UserName nvarchar(64),
	@IPAddress nvarchar(50),
	@Description ntext
)AS

	INSERT INTO [Hishop_Logs]([ResourceName],[OperationName],[PageUrl],[AddedTime],[UserName],[IPAddress],[Description])
	VALUES(@ResourceName,@OperationName,@PageUrl,@AddedTime,@UserName,@IPAddress,@Description)' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_ManageLogs_Delete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_ManageLogs_Delete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_ManageLogs_Delete]
	@LogId int
AS
	SET Transaction Isolation Level Read UNCOMMITTED
	DELETE FROM Hishop_Logs WHERE LogId = @LogId' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_GetNumberOfUsersOnline]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_GetNumberOfUsersOnline]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_GetNumberOfUsersOnline]
    @ApplicationName            nvarchar(256),
    @MinutesSinceLastInActive   int,
    @CurrentTimeUtc             datetime
AS
BEGIN
    DECLARE @DateActive datetime
    SELECT  @DateActive = DATEADD(minute,  -(@MinutesSinceLastInActive), @CurrentTimeUtc)

    DECLARE @NumOnline int
    SELECT  @NumOnline = COUNT(*)
    FROM    dbo.aspnet_Users u(NOLOCK),
            dbo.aspnet_Applications a(NOLOCK),
            dbo.aspnet_Membership m(NOLOCK)
    WHERE   u.ApplicationId = a.ApplicationId                  AND
            LastActivityDate > @DateActive                     AND
            a.LoweredApplicationName = LOWER(@ApplicationName) AND
            u.UserId = m.UserId
    RETURN(@NumOnline)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_GetUserByEmail]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_GetUserByEmail]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_GetUserByEmail]
    @ApplicationName  nvarchar(256),
    @Email            nvarchar(256)
AS
BEGIN
    IF( @Email IS NULL )
        SELECT  u.UserName
        FROM    dbo.aspnet_Applications a, dbo.aspnet_Users u, dbo.aspnet_Membership m
        WHERE   LOWER(@ApplicationName) = a.LoweredApplicationName AND
                u.ApplicationId = a.ApplicationId    AND
                u.UserId = m.UserId AND
                m.LoweredEmail IS NULL
    ELSE
        SELECT  u.UserName
        FROM    dbo.aspnet_Applications a, dbo.aspnet_Users u, dbo.aspnet_Membership m
        WHERE   LOWER(@ApplicationName) = a.LoweredApplicationName AND
                u.ApplicationId = a.ApplicationId    AND
                u.UserId = m.UserId AND
                LOWER(@Email) = m.LoweredEmail

    IF (@@rowcount = 0)
        RETURN(1)
    RETURN(0)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_User_PasswordAnswer_Change]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_User_PasswordAnswer_Change]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_User_PasswordAnswer_Change]
(
	@UserId int,
	@PasswordQuestion  nvarchar(256),
	@PasswordAnswer  nvarchar(256)
)
AS

Declare @UID uniqueidentifier
Select @UID = MembershipId FROM Hishop_UserProfile where UserId = @UserId

BEGIN
	UPDATE
		aspnet_membership
	SET
		PasswordQuestion = @PasswordQuestion,
		PasswordAnswer = @PasswordAnswer
	WHERE
		UserId = @UID
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_GetPasswordWithFormat]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_GetPasswordWithFormat]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_GetPasswordWithFormat]
    @ApplicationName                nvarchar(256),
    @UserName                       nvarchar(256),
    @UpdateLastLoginActivityDate    bit,
    @CurrentTimeUtc                 datetime
AS
BEGIN
    DECLARE @IsLockedOut                        bit
    DECLARE @UserId                             uniqueidentifier
    DECLARE @Password                           nvarchar(128)
    DECLARE @PasswordSalt                       nvarchar(128)
    DECLARE @PasswordFormat                     int
    DECLARE @FailedPasswordAttemptCount         int
    DECLARE @FailedPasswordAnswerAttemptCount   int
    DECLARE @IsApproved                         bit
    DECLARE @LastActivityDate                   datetime
    DECLARE @LastLoginDate                      datetime

    SELECT  @UserId          = NULL

    SELECT  @UserId = u.UserId, @IsLockedOut = m.IsLockedOut, @Password=Password, @PasswordFormat=PasswordFormat,
            @PasswordSalt=PasswordSalt, @FailedPasswordAttemptCount=FailedPasswordAttemptCount,
		    @FailedPasswordAnswerAttemptCount=FailedPasswordAnswerAttemptCount, @IsApproved=IsApproved,
            @LastActivityDate = LastActivityDate, @LastLoginDate = LastLoginDate
    FROM    dbo.aspnet_Applications a, dbo.aspnet_Users u, dbo.aspnet_Membership m
    WHERE   LOWER(@ApplicationName) = a.LoweredApplicationName AND
            u.ApplicationId = a.ApplicationId    AND
            u.UserId = m.UserId AND
            LOWER(@UserName) = u.LoweredUserName

    IF (@UserId IS NULL)
        RETURN 1

    IF (@IsLockedOut = 1)
        RETURN 99

    SELECT   @Password, @PasswordFormat, @PasswordSalt, @FailedPasswordAttemptCount,
             @FailedPasswordAnswerAttemptCount, @IsApproved, @LastLoginDate, @LastActivityDate

    IF (@UpdateLastLoginActivityDate = 1 AND @IsApproved = 1)
    BEGIN
        UPDATE  dbo.aspnet_Membership
        SET     LastLoginDate = @CurrentTimeUtc
        WHERE   UserId = @UserId

        UPDATE  dbo.aspnet_Users
        SET     LastActivityDate = @CurrentTimeUtc
        WHERE   @UserId = UserId
    END


    RETURN 0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_GetUserByName]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_GetUserByName]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_GetUserByName]
    @ApplicationName      nvarchar(256),
    @UserName             nvarchar(256),
    @CurrentTimeUtc       datetime,
    @UpdateLastActivity   bit = 0
AS
BEGIN
    DECLARE @UserId uniqueidentifier

    IF (@UpdateLastActivity = 1)
    BEGIN
        SELECT TOP 1 m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
                m.CreateDate, m.LastLoginDate, @CurrentTimeUtc, m.LastPasswordChangedDate,
                u.UserId, m.IsLockedOut,m.LastLockoutDate
        FROM    dbo.aspnet_Applications a, dbo.aspnet_Users u, dbo.aspnet_Membership m
        WHERE    LOWER(@ApplicationName) = a.LoweredApplicationName AND
                u.ApplicationId = a.ApplicationId    AND
                LOWER(@UserName) = u.LoweredUserName AND u.UserId = m.UserId

        IF (@@ROWCOUNT = 0) -- Username not found
            RETURN -1

        UPDATE   dbo.aspnet_Users
        SET      LastActivityDate = @CurrentTimeUtc
        WHERE    @UserId = UserId
    END
    ELSE
    BEGIN
        SELECT TOP 1 m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
                m.CreateDate, m.LastLoginDate, u.LastActivityDate, m.LastPasswordChangedDate,
                u.UserId, m.IsLockedOut,m.LastLockoutDate
        FROM    dbo.aspnet_Applications a, dbo.aspnet_Users u, dbo.aspnet_Membership m
        WHERE    LOWER(@ApplicationName) = a.LoweredApplicationName AND
                u.ApplicationId = a.ApplicationId    AND
                LOWER(@UserName) = u.LoweredUserName AND u.UserId = m.UserId

        IF (@@ROWCOUNT = 0) -- Username not found
            RETURN -1
    END

    RETURN 0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_GetPassword]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_GetPassword]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_GetPassword]
    @ApplicationName                nvarchar(256),
    @UserName                       nvarchar(256),
    @MaxInvalidPasswordAttempts     int,
    @PasswordAttemptWindow          int,
    @CurrentTimeUtc                 datetime,
    @PasswordAnswer                 nvarchar(128) = NULL
AS
BEGIN
    DECLARE @UserId                                 uniqueidentifier
    DECLARE @PasswordFormat                         int
    DECLARE @Password                               nvarchar(128)
    DECLARE @passAns                                nvarchar(128)
    DECLARE @IsLockedOut                            bit
    DECLARE @LastLockoutDate                        datetime
    DECLARE @FailedPasswordAttemptCount             int
    DECLARE @FailedPasswordAttemptWindowStart       datetime
    DECLARE @FailedPasswordAnswerAttemptCount       int
    DECLARE @FailedPasswordAnswerAttemptWindowStart datetime

    DECLARE @ErrorCode     int
    SET @ErrorCode = 0

    DECLARE @TranStarted   bit
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
	    BEGIN TRANSACTION
	    SET @TranStarted = 1
    END
    ELSE
    	SET @TranStarted = 0

    SELECT  @UserId = u.UserId,
            @Password = m.Password,
            @passAns = m.PasswordAnswer,
            @PasswordFormat = m.PasswordFormat,
            @IsLockedOut = m.IsLockedOut,
            @LastLockoutDate = m.LastLockoutDate,
            @FailedPasswordAttemptCount = m.FailedPasswordAttemptCount,
            @FailedPasswordAttemptWindowStart = m.FailedPasswordAttemptWindowStart,
            @FailedPasswordAnswerAttemptCount = m.FailedPasswordAnswerAttemptCount,
            @FailedPasswordAnswerAttemptWindowStart = m.FailedPasswordAnswerAttemptWindowStart
    FROM    dbo.aspnet_Applications a, dbo.aspnet_Users u, dbo.aspnet_Membership m WITH ( UPDLOCK )
    WHERE   LOWER(@ApplicationName) = a.LoweredApplicationName AND
            u.ApplicationId = a.ApplicationId    AND
            u.UserId = m.UserId AND
            LOWER(@UserName) = u.LoweredUserName

    IF ( @@rowcount = 0 )
    BEGIN
        SET @ErrorCode = 1
        GOTO Cleanup
    END

    IF( @IsLockedOut = 1 )
    BEGIN
        SET @ErrorCode = 99
        GOTO Cleanup
    END

    IF ( NOT( @PasswordAnswer IS NULL ) )
    BEGIN
        IF( ( @passAns IS NULL ) OR ( LOWER( @passAns ) <> LOWER( @PasswordAnswer ) ) )
        BEGIN
            IF( @CurrentTimeUtc > DATEADD( minute, @PasswordAttemptWindow, @FailedPasswordAnswerAttemptWindowStart ) )
            BEGIN
                SET @FailedPasswordAnswerAttemptWindowStart = @CurrentTimeUtc
                SET @FailedPasswordAnswerAttemptCount = 1
            END
            ELSE
            BEGIN
                SET @FailedPasswordAnswerAttemptCount = @FailedPasswordAnswerAttemptCount + 1
                SET @FailedPasswordAnswerAttemptWindowStart = @CurrentTimeUtc
            END

            BEGIN
                IF( @FailedPasswordAnswerAttemptCount >= @MaxInvalidPasswordAttempts )
                BEGIN
                    SET @IsLockedOut = 1
                    SET @LastLockoutDate = @CurrentTimeUtc
                END
            END

            SET @ErrorCode = 3
        END
        ELSE
        BEGIN
            IF( @FailedPasswordAnswerAttemptCount > 0 )
            BEGIN
                SET @FailedPasswordAnswerAttemptCount = 0
                SET @FailedPasswordAnswerAttemptWindowStart = CONVERT( datetime, ''17540101'', 112 )
            END
        END

        UPDATE dbo.aspnet_Membership
        SET IsLockedOut = @IsLockedOut, LastLockoutDate = @LastLockoutDate,
            FailedPasswordAttemptCount = @FailedPasswordAttemptCount,
            FailedPasswordAttemptWindowStart = @FailedPasswordAttemptWindowStart,
            FailedPasswordAnswerAttemptCount = @FailedPasswordAnswerAttemptCount,
            FailedPasswordAnswerAttemptWindowStart = @FailedPasswordAnswerAttemptWindowStart
        WHERE @UserId = UserId

        IF( @@ERROR <> 0 )
        BEGIN
            SET @ErrorCode = -1
            GOTO Cleanup
        END
    END

    IF( @TranStarted = 1 )
    BEGIN
	SET @TranStarted = 0
	COMMIT TRANSACTION
    END

    IF( @ErrorCode = 0 )
        SELECT @Password, @PasswordFormat

    RETURN @ErrorCode

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_GetUserByUserId]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_GetUserByUserId]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_GetUserByUserId]
    @UserId               uniqueidentifier,
    @CurrentTimeUtc       datetime,
    @UpdateLastActivity   bit = 0
AS
BEGIN
    IF ( @UpdateLastActivity = 1 )
    BEGIN
        UPDATE   dbo.aspnet_Users
        SET      LastActivityDate = @CurrentTimeUtc
        FROM     dbo.aspnet_Users
        WHERE    @UserId = UserId

        IF ( @@ROWCOUNT = 0 ) -- User ID not found
            RETURN -1
    END

    SELECT  m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
            m.CreateDate, m.LastLoginDate, u.LastActivityDate,
            m.LastPasswordChangedDate, u.UserName, m.IsLockedOut,
            m.LastLockoutDate
    FROM    dbo.aspnet_Users u, dbo.aspnet_Membership m
    WHERE   @UserId = u.UserId AND u.UserId = m.UserId

    IF ( @@ROWCOUNT = 0 ) -- User ID not found
       RETURN -1

    RETURN 0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_ResetPassword]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_ResetPassword]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_ResetPassword]
    @ApplicationName             nvarchar(256),
    @UserName                    nvarchar(256),
    @NewPassword                 nvarchar(128),
    @MaxInvalidPasswordAttempts  int,
    @PasswordAttemptWindow       int,
    @PasswordSalt                nvarchar(128),
    @CurrentTimeUtc              datetime,
    @PasswordFormat              int = 0,
    @PasswordAnswer              nvarchar(128) = NULL
AS
BEGIN
    DECLARE @IsLockedOut                            bit
    DECLARE @LastLockoutDate                        datetime
    DECLARE @FailedPasswordAttemptCount             int
    DECLARE @FailedPasswordAttemptWindowStart       datetime
    DECLARE @FailedPasswordAnswerAttemptCount       int
    DECLARE @FailedPasswordAnswerAttemptWindowStart datetime

    DECLARE @UserId                                 uniqueidentifier
    SET     @UserId = NULL

    DECLARE @ErrorCode     int
    SET @ErrorCode = 0

    DECLARE @TranStarted   bit
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
	    BEGIN TRANSACTION
	    SET @TranStarted = 1
    END
    ELSE
    	SET @TranStarted = 0

    SELECT  @UserId = u.UserId
    FROM    dbo.aspnet_Users u, dbo.aspnet_Applications a, dbo.aspnet_Membership m
    WHERE   LoweredUserName = LOWER(@UserName) AND
            u.ApplicationId = a.ApplicationId  AND
            LOWER(@ApplicationName) = a.LoweredApplicationName AND
            u.UserId = m.UserId

    IF ( @UserId IS NULL )
    BEGIN
        SET @ErrorCode = 1
        GOTO Cleanup
    END

    SELECT @IsLockedOut = IsLockedOut,
           @LastLockoutDate = LastLockoutDate,
           @FailedPasswordAttemptCount = FailedPasswordAttemptCount,
           @FailedPasswordAttemptWindowStart = FailedPasswordAttemptWindowStart,
           @FailedPasswordAnswerAttemptCount = FailedPasswordAnswerAttemptCount,
           @FailedPasswordAnswerAttemptWindowStart = FailedPasswordAnswerAttemptWindowStart
    FROM dbo.aspnet_Membership WITH ( UPDLOCK )
    WHERE @UserId = UserId

    IF( @IsLockedOut = 1 )
    BEGIN
        SET @ErrorCode = 99
        GOTO Cleanup
    END

    UPDATE dbo.aspnet_Membership
    SET    Password = @NewPassword,
           LastPasswordChangedDate = @CurrentTimeUtc,
           PasswordFormat = @PasswordFormat,
           PasswordSalt = @PasswordSalt
    WHERE  @UserId = UserId AND
           ( ( @PasswordAnswer IS NULL ) OR ( LOWER( PasswordAnswer ) = LOWER( @PasswordAnswer ) ) )

    IF ( @@ROWCOUNT = 0 )
        BEGIN
            IF( @CurrentTimeUtc > DATEADD( minute, @PasswordAttemptWindow, @FailedPasswordAnswerAttemptWindowStart ) )
            BEGIN
                SET @FailedPasswordAnswerAttemptWindowStart = @CurrentTimeUtc
                SET @FailedPasswordAnswerAttemptCount = 1
            END
            ELSE
            BEGIN
                SET @FailedPasswordAnswerAttemptWindowStart = @CurrentTimeUtc
                SET @FailedPasswordAnswerAttemptCount = @FailedPasswordAnswerAttemptCount + 1
            END

            BEGIN
                IF( @FailedPasswordAnswerAttemptCount >= @MaxInvalidPasswordAttempts )
                BEGIN
                    SET @IsLockedOut = 1
                    SET @LastLockoutDate = @CurrentTimeUtc
                END
            END

            SET @ErrorCode = 3
        END
    ELSE
        BEGIN
            IF( @FailedPasswordAnswerAttemptCount > 0 )
            BEGIN
                SET @FailedPasswordAnswerAttemptCount = 0
                SET @FailedPasswordAnswerAttemptWindowStart = CONVERT( datetime, ''17540101'', 112 )
            END
        END

    IF( NOT ( @PasswordAnswer IS NULL ) )
    BEGIN
        UPDATE dbo.aspnet_Membership
        SET IsLockedOut = @IsLockedOut, LastLockoutDate = @LastLockoutDate,
            FailedPasswordAttemptCount = @FailedPasswordAttemptCount,
            FailedPasswordAttemptWindowStart = @FailedPasswordAttemptWindowStart,
            FailedPasswordAnswerAttemptCount = @FailedPasswordAnswerAttemptCount,
            FailedPasswordAnswerAttemptWindowStart = @FailedPasswordAnswerAttemptWindowStart
        WHERE @UserId = UserId

        IF( @@ERROR <> 0 )
        BEGIN
            SET @ErrorCode = -1
            GOTO Cleanup
        END
    END

    IF( @TranStarted = 1 )
    BEGIN
	SET @TranStarted = 0
	COMMIT TRANSACTION
    END

    RETURN @ErrorCode

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_ChangePasswordQuestionAndAnswer]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_ChangePasswordQuestionAndAnswer]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_ChangePasswordQuestionAndAnswer]
    @ApplicationName       nvarchar(256),
    @UserName              nvarchar(256),
    @NewPasswordQuestion   nvarchar(256),
    @NewPasswordAnswer     nvarchar(128)
AS
BEGIN
    DECLARE @UserId uniqueidentifier
    SELECT  @UserId = NULL
    SELECT  @UserId = u.UserId
    FROM    dbo.aspnet_Membership m, dbo.aspnet_Users u, dbo.aspnet_Applications a
    WHERE   LoweredUserName = LOWER(@UserName) AND
            u.ApplicationId = a.ApplicationId  AND
            LOWER(@ApplicationName) = a.LoweredApplicationName AND
            u.UserId = m.UserId
    IF (@UserId IS NULL)
    BEGIN
        RETURN(1)
    END

    UPDATE dbo.aspnet_Membership
    SET    PasswordQuestion = @NewPasswordQuestion, PasswordAnswer = @NewPasswordAnswer
    WHERE  UserId=@UserId
    RETURN(0)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_UpdateUserInfo]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_UpdateUserInfo]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_UpdateUserInfo]
    @ApplicationName                nvarchar(256),
    @UserName                       nvarchar(256),
    @IsPasswordCorrect              bit,
    @UpdateLastLoginActivityDate    bit,
    @MaxInvalidPasswordAttempts     int,
    @PasswordAttemptWindow          int,
    @CurrentTimeUtc                 datetime,
    @LastLoginDate                  datetime,
    @LastActivityDate               datetime
AS
BEGIN
    DECLARE @UserId                                 uniqueidentifier
    DECLARE @IsApproved                             bit
    DECLARE @IsLockedOut                            bit
    DECLARE @LastLockoutDate                        datetime
    DECLARE @FailedPasswordAttemptCount             int
    DECLARE @FailedPasswordAttemptWindowStart       datetime
    DECLARE @FailedPasswordAnswerAttemptCount       int
    DECLARE @FailedPasswordAnswerAttemptWindowStart datetime

    DECLARE @ErrorCode     int
    SET @ErrorCode = 0

    DECLARE @TranStarted   bit
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
	    BEGIN TRANSACTION
	    SET @TranStarted = 1
    END
    ELSE
    	SET @TranStarted = 0

    SELECT  @UserId = u.UserId,
            @IsApproved = m.IsApproved,
            @IsLockedOut = m.IsLockedOut,
            @LastLockoutDate = m.LastLockoutDate,
            @FailedPasswordAttemptCount = m.FailedPasswordAttemptCount,
            @FailedPasswordAttemptWindowStart = m.FailedPasswordAttemptWindowStart,
            @FailedPasswordAnswerAttemptCount = m.FailedPasswordAnswerAttemptCount,
            @FailedPasswordAnswerAttemptWindowStart = m.FailedPasswordAnswerAttemptWindowStart
    FROM    dbo.aspnet_Applications a, dbo.aspnet_Users u, dbo.aspnet_Membership m WITH ( UPDLOCK )
    WHERE   LOWER(@ApplicationName) = a.LoweredApplicationName AND
            u.ApplicationId = a.ApplicationId    AND
            u.UserId = m.UserId AND
            LOWER(@UserName) = u.LoweredUserName

    IF ( @@rowcount = 0 )
    BEGIN
        SET @ErrorCode = 1
        GOTO Cleanup
    END

    IF( @IsLockedOut = 1 )
    BEGIN
        GOTO Cleanup
    END

    IF( @IsPasswordCorrect = 0 )
    BEGIN
        IF( @CurrentTimeUtc > DATEADD( minute, @PasswordAttemptWindow, @FailedPasswordAttemptWindowStart ) )
        BEGIN
            SET @FailedPasswordAttemptWindowStart = @CurrentTimeUtc
            SET @FailedPasswordAttemptCount = 1
        END
        ELSE
        BEGIN
            SET @FailedPasswordAttemptWindowStart = @CurrentTimeUtc
            SET @FailedPasswordAttemptCount = @FailedPasswordAttemptCount + 1
        END

        BEGIN
            IF( @FailedPasswordAttemptCount >= @MaxInvalidPasswordAttempts )
            BEGIN
                SET @IsLockedOut = 1
                SET @LastLockoutDate = @CurrentTimeUtc
            END
        END
    END
    ELSE
    BEGIN
        IF( @FailedPasswordAttemptCount > 0 OR @FailedPasswordAnswerAttemptCount > 0 )
        BEGIN
            SET @FailedPasswordAttemptCount = 0
            SET @FailedPasswordAttemptWindowStart = CONVERT( datetime, ''17540101'', 112 )
            SET @FailedPasswordAnswerAttemptCount = 0
            SET @FailedPasswordAnswerAttemptWindowStart = CONVERT( datetime, ''17540101'', 112 )
            SET @LastLockoutDate = CONVERT( datetime, ''17540101'', 112 )
        END
    END

    IF( @UpdateLastLoginActivityDate = 1 )
    BEGIN
        UPDATE  dbo.aspnet_Users
        SET     LastActivityDate = @LastActivityDate
        WHERE   @UserId = UserId

        IF( @@ERROR <> 0 )
        BEGIN
            SET @ErrorCode = -1
            GOTO Cleanup
        END

        UPDATE  dbo.aspnet_Membership
        SET     LastLoginDate = @LastLoginDate
        WHERE   UserId = @UserId

        IF( @@ERROR <> 0 )
        BEGIN
            SET @ErrorCode = -1
            GOTO Cleanup
        END
    END


    UPDATE dbo.aspnet_Membership
    SET IsLockedOut = @IsLockedOut, LastLockoutDate = @LastLockoutDate,
        FailedPasswordAttemptCount = @FailedPasswordAttemptCount,
        FailedPasswordAttemptWindowStart = @FailedPasswordAttemptWindowStart,
        FailedPasswordAnswerAttemptCount = @FailedPasswordAnswerAttemptCount,
        FailedPasswordAnswerAttemptWindowStart = @FailedPasswordAnswerAttemptWindowStart
    WHERE @UserId = UserId

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF( @TranStarted = 1 )
    BEGIN
	SET @TranStarted = 0
	COMMIT TRANSACTION
    END

    RETURN @ErrorCode

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END' 
END
GO
/****** Object:  View [dbo].[vw_aspnet_MembershipUsers]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[vw_aspnet_MembershipUsers]') AND OBJECTPROPERTY(id, N'IsView') = 1)
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vw_aspnet_MembershipUsers]
  AS SELECT [dbo].[aspnet_Membership].[UserId],
            [dbo].[aspnet_Membership].[PasswordFormat],
            [dbo].[aspnet_Membership].[MobilePIN],
            [dbo].[aspnet_Membership].[Email],
            [dbo].[aspnet_Membership].[LoweredEmail],
            [dbo].[aspnet_Membership].[PasswordQuestion],
            [dbo].[aspnet_Membership].[PasswordAnswer],
            [dbo].[aspnet_Membership].[IsApproved],
            [dbo].[aspnet_Membership].[IsLockedOut],
            [dbo].[aspnet_Membership].[CreateDate],
            [dbo].[aspnet_Membership].[LastLoginDate],
            [dbo].[aspnet_Membership].[LastPasswordChangedDate],
            [dbo].[aspnet_Membership].[LastLockoutDate],
            [dbo].[aspnet_Membership].[FailedPasswordAttemptCount],
            [dbo].[aspnet_Membership].[FailedPasswordAttemptWindowStart],
            [dbo].[aspnet_Membership].[FailedPasswordAnswerAttemptCount],
            [dbo].[aspnet_Membership].[FailedPasswordAnswerAttemptWindowStart],
            [dbo].[aspnet_Membership].[Comment],
            [dbo].[aspnet_Users].[ApplicationId],
            [dbo].[aspnet_Users].[UserName],
            [dbo].[aspnet_Users].[MobileAlias],
            [dbo].[aspnet_Users].[IsAnonymous],
            [dbo].[aspnet_Users].[LastActivityDate]
  FROM [dbo].[aspnet_Membership] INNER JOIN [dbo].[aspnet_Users]
      ON [dbo].[aspnet_Membership].[UserId] = [dbo].[aspnet_Users].[UserId]'
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_UpdateUser]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_UpdateUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_UpdateUser]
    @ApplicationName      nvarchar(256),
    @UserName             nvarchar(256),
    @Email                nvarchar(256),
    @Comment              ntext,
    @IsApproved           bit,
    @LastLoginDate        datetime,
    @LastActivityDate     datetime,
    @UniqueEmail          int,
    @CurrentTimeUtc       datetime
AS
BEGIN
    DECLARE @UserId uniqueidentifier
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @UserId = NULL
    SELECT  @UserId = u.UserId, @ApplicationId = a.ApplicationId
    FROM    dbo.aspnet_Users u, dbo.aspnet_Applications a, dbo.aspnet_Membership m
    WHERE   LoweredUserName = LOWER(@UserName) AND
            u.ApplicationId = a.ApplicationId  AND
            LOWER(@ApplicationName) = a.LoweredApplicationName AND
            u.UserId = m.UserId

    IF (@UserId IS NULL)
        RETURN(1)

    IF (@UniqueEmail = 1)
    BEGIN
        IF (EXISTS (SELECT *
                    FROM  dbo.aspnet_Membership WITH (UPDLOCK, HOLDLOCK)
                    WHERE ApplicationId = @ApplicationId  AND @UserId <> UserId AND LoweredEmail = LOWER(@Email)))
        BEGIN
            RETURN(7)
        END
    END

    DECLARE @TranStarted   bit
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
	    BEGIN TRANSACTION
	    SET @TranStarted = 1
    END
    ELSE
	SET @TranStarted = 0

    UPDATE dbo.aspnet_Users WITH (ROWLOCK)
    SET
         LastActivityDate = @LastActivityDate
    WHERE
       @UserId = UserId

    IF( @@ERROR <> 0 )
        GOTO Cleanup

    UPDATE dbo.aspnet_Membership WITH (ROWLOCK)
    SET
         Email            = @Email,
         LoweredEmail     = LOWER(@Email),
         Comment          = @Comment,
         IsApproved       = @IsApproved,
         LastLoginDate    = @LastLoginDate
    WHERE
       @UserId = UserId

    IF( @@ERROR <> 0 )
        GOTO Cleanup

    IF( @TranStarted = 1 )
    BEGIN
	SET @TranStarted = 0
	COMMIT TRANSACTION
    END

    RETURN 0

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END

    RETURN -1
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_UnlockUser]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_UnlockUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_UnlockUser]
    @ApplicationName                         nvarchar(256),
    @UserName                                nvarchar(256)
AS
BEGIN
    DECLARE @UserId uniqueidentifier
    SELECT  @UserId = NULL
    SELECT  @UserId = u.UserId
    FROM    dbo.aspnet_Users u, dbo.aspnet_Applications a, dbo.aspnet_Membership m
    WHERE   LoweredUserName = LOWER(@UserName) AND
            u.ApplicationId = a.ApplicationId  AND
            LOWER(@ApplicationName) = a.LoweredApplicationName AND
            u.UserId = m.UserId

    IF ( @UserId IS NULL )
        RETURN 1

    UPDATE dbo.aspnet_Membership
    SET IsLockedOut = 0,
        FailedPasswordAttemptCount = 0,
        FailedPasswordAttemptWindowStart = CONVERT( datetime, ''17540101'', 112 ),
        FailedPasswordAnswerAttemptCount = 0,
        FailedPasswordAnswerAttemptWindowStart = CONVERT( datetime, ''17540101'', 112 ),
        LastLockoutDate = CONVERT( datetime, ''17540101'', 112 )
    WHERE @UserId = UserId

    RETURN 0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Users_ValidateAnswereAnswer]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Users_ValidateAnswereAnswer]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_Users_ValidateAnswereAnswer]
(
	@UserId uniqueidentifier,
	@PasswordAnswer nvarchar(128),
	@IsValid bit output
)
as

if exists (Select UserId from aspnet_membership where Lower(PasswordAnswer) = Lower(@PasswordAnswer))
Begin
	Set @IsValid = 1
End
Else
Begin
	Set @IsValid = 0
End' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_SetPassword]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_SetPassword]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_SetPassword]
    @ApplicationName  nvarchar(256),
    @UserName         nvarchar(256),
    @NewPassword      nvarchar(128),
    @PasswordSalt     nvarchar(128),
    @CurrentTimeUtc   datetime,
    @PasswordFormat   int = 0
AS
BEGIN
    DECLARE @UserId uniqueidentifier
    SELECT  @UserId = NULL
    SELECT  @UserId = u.UserId
    FROM    dbo.aspnet_Users u, dbo.aspnet_Applications a, dbo.aspnet_Membership m
    WHERE   LoweredUserName = LOWER(@UserName) AND
            u.ApplicationId = a.ApplicationId  AND
            LOWER(@ApplicationName) = a.LoweredApplicationName AND
            u.UserId = m.UserId

    IF (@UserId IS NULL)
        RETURN(1)

    UPDATE dbo.aspnet_Membership
    SET Password = @NewPassword, PasswordFormat = @PasswordFormat, PasswordSalt = @PasswordSalt,
        LastPasswordChangedDate = @CurrentTimeUtc
    WHERE @UserId = UserId
    RETURN(0)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_OnlineServiceItem_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_OnlineServiceItem_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_OnlineServiceItem_CreateUpdateDelete]
	(
		@ServiceId BIGINT = NULL,
		@DisplaySequence INT = NULL,
		@ServiceAccount NVARCHAR(200) = NULL,
		@ServiceType INT =NULL,
		@IsShowItem BIT = NULL,
		@ServiceName NVARCHAR(100)=NULL,
		@Action INT,
		@IsMemberCreated BIT = 0,
		@UserId INT = 0,
		@Status INT OUTPUT
	)
AS	
    DECLARE @intErrorCode INT
	-- 初始化信息
	SELECT @Status = 99, @intErrorCode = 0
	
	IF @Action = 2 -- 删除
	BEGIN 
	
		SET XACT_ABORT ON
		
		BEGIN TRAN
		
		DELETE FROM Hishop_OnlineServiceItem WHERE ServiceId = @ServiceId
		SET @intErrorCode = @@ERROR
			
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
			COMMIT TRAN
		END
		ELSE
			ROLLBACK TRAN
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN
	
		--如果排序编号在此兄弟节点间存在,则修改分类中兄弟节点的其它的排序编号
		IF EXISTS(SELECT DisplaySequence FROM Hishop_OnlineServiceItem WHERE DisplaySequence = @DisplaySequence) 
		-- 将大于或等于其兄弟节点的排序号加1
			UPDATE Hishop_OnlineServiceItem SET DisplaySequence = DisplaySequence + 1 WHERE DisplaySequence >=@DisplaySequence
		
		INSERT INTO Hishop_OnlineServiceItem
			([ServiceAccount], ServiceType, DisplaySequence, IsShowItem,ServiceName, IsMemberCreated, UserId)
		VALUES 
			(@ServiceAccount, @ServiceType, @DisplaySequence, @IsShowItem,@ServiceName, @IsMemberCreated, @UserId)
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
			--如果排序编号在此兄弟节点间存在,则修改分类中兄弟节点的其它的排序编号
		IF EXISTS(SELECT DisplaySequence FROM Hishop_OnlineServiceItem WHERE DisplaySequence = @DisplaySequence AND ServiceId!=@ServiceId) 
		-- 将大于或等于其兄弟节点的排序号加1
			UPDATE Hishop_OnlineServiceItem SET DisplaySequence = DisplaySequence + 1 WHERE DisplaySequence >=@DisplaySequence
			
		-- 修改分类信息
		UPDATE 
			Hishop_OnlineServiceItem 
		SET 
			[ServiceAccount] = @ServiceAccount,
			DisplaySequence = @DisplaySequence,
			ServiceType = @ServiceType,
			IsShowItem = @IsShowItem,
			ServiceName = @ServiceName

		WHERE ServiceId = @ServiceId
		
		SET @intErrorCode = @intErrorCode + @@ERROR
		
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
		END
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_OnlineServiceItem_Sequence]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_OnlineServiceItem_Sequence]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_OnlineServiceItem_Sequence]
(
  @Sort INT , -- 是升 还是降 1 表示升 2表示降
  @ServiceId INT
)
As 
    --  当前要修改的序号
	 DECLARE @oldSequence INT
	 -- 要修改成的序号
	 DECLARE @newSequence INT
	 -- 和当前对换的编号
	 DECLARE @newServiceId INT
 --升
 IF @Sort =1
    
 BEGIN
	
	 SELECT @oldSequence = DisplaySequence FROM [Hishop_OnlineServiceItem]
     WHERE ServiceId =@ServiceId
 
     SELECT @newSequence = DisplaySequence FROM [Hishop_OnlineServiceItem]
     WHERE ServiceId =
		(SELECT TOP 1 ServiceId FROM [Hishop_OnlineServiceItem]
		WHERE DisplaySequence < @oldSequence
		Order by DisplaySequence DESC)

     SELECT @newServiceId = (SELECT TOP 1 ServiceId FROM [Hishop_OnlineServiceItem]
     WHERE DisplaySequence < @oldSequence
     ORDER BY DisplaySequence DESC)
    
    IF @newServiceId IS NOT NULL
     BEGIN
		  Update [Hishop_OnlineServiceItem] SET DisplaySequence =@newSequence 
		  WHERE ServiceId = @ServiceId
     END
    IF @newServiceId IS NOT NULL
     BEGIN
		  Update [Hishop_OnlineServiceItem] SET DisplaySequence = @oldSequence
		  WHERE ServiceId = @newServiceId 
     END
  END 
 --降低
 IF @Sort =0
 BEGIN
	SELECT @oldSequence = DisplaySequence FROM [Hishop_OnlineServiceItem]
	WHERE ServiceId =@ServiceId 
	 
	SELECT @newSequence = DisplaySequence FROM [Hishop_OnlineServiceItem]
	WHERE ServiceId =
		 (SELECT TOP 1 ServiceId FROM [Hishop_OnlineServiceItem]
		 WHERE DisplaySequence>@oldSequence 
		 Order by DisplaySequence ASC) 
	 
	SELECT @newServiceId = (SELECT TOP 1 ServiceId FROM [Hishop_OnlineServiceItem]
	WHERE DisplaySequence > @oldSequence 
	Order by DisplaySequence ASC)
    
    IF @newSequence IS NOT NULL
     BEGIN
		  UPDATE [Hishop_OnlineServiceItem] SET DisplaySequence =@newSequence 
		  WHERE ServiceId = @ServiceId 
     END
    IF @newServiceId IS NOT NULL
     BEGIN
		  UPDATE [Hishop_OnlineServiceItem] Set DisplaySequence = @oldSequence
		  WHERE ServiceId =@newServiceId 
     END
 END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Profile_GetProfiles]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Profile_GetProfiles]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Profile_GetProfiles]
    @ApplicationName        nvarchar(256),
    @ProfileAuthOptions     int,
    @PageIndex              int,
    @PageSize               int,
    @UserNameToMatch        nvarchar(256) = NULL,
    @InactiveSinceDate      datetime      = NULL
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN

    -- Set the page bounds
    DECLARE @PageLowerBound int
    DECLARE @PageUpperBound int
    DECLARE @TotalRecords   int
    SET @PageLowerBound = @PageSize * (@PageIndex-1)
    SET @PageUpperBound = @PageSize - 1 + @PageLowerBound

    -- Create a temp table TO store the select results
    CREATE TABLE #PageIndexForUsers
    (
        IndexId int IDENTITY (0, 1) NOT NULL,
        UserId uniqueidentifier
    )

    -- Insert into our temp table
    INSERT INTO #PageIndexForUsers (UserId)
        SELECT  u.UserId
        FROM    dbo.aspnet_Users u, dbo.aspnet_Profile p
        WHERE   ApplicationId = @ApplicationId
            AND u.UserId = p.UserId
            AND (@InactiveSinceDate IS NULL OR LastActivityDate <= @InactiveSinceDate)
            AND (     (@ProfileAuthOptions = 2)
                   OR (@ProfileAuthOptions = 0 AND IsAnonymous = 1)
                   OR (@ProfileAuthOptions = 1 AND IsAnonymous = 0)
                 )
            AND (@UserNameToMatch IS NULL OR LoweredUserName LIKE LOWER(@UserNameToMatch))
        ORDER BY UserName

    SELECT  u.UserName, u.IsAnonymous, u.LastActivityDate, p.LastUpdatedDate,
            DATALENGTH(p.PropertyNames) + DATALENGTH(p.PropertyValuesString) + DATALENGTH(p.PropertyValuesBinary)
    FROM    dbo.aspnet_Users u, dbo.aspnet_Profile p, #PageIndexForUsers i
    WHERE   u.UserId = p.UserId AND p.UserId = i.UserId AND i.IndexId >= @PageLowerBound AND i.IndexId <= @PageUpperBound

    SELECT COUNT(*)
    FROM   #PageIndexForUsers

    DROP TABLE #PageIndexForUsers
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Applications_CreateApplication]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Applications_CreateApplication]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Applications_CreateApplication]
    @ApplicationName      nvarchar(256),
    @ApplicationId        uniqueidentifier OUTPUT
AS
BEGIN
    SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName

    IF(@ApplicationId IS NULL)
    BEGIN
        DECLARE @TranStarted   bit
        SET @TranStarted = 0

        IF( @@TRANCOUNT = 0 )
        BEGIN
	        BEGIN TRANSACTION
	        SET @TranStarted = 1
        END
        ELSE
    	    SET @TranStarted = 0

        SELECT  @ApplicationId = ApplicationId
        FROM dbo.aspnet_Applications WITH (UPDLOCK, HOLDLOCK)
        WHERE LOWER(@ApplicationName) = LoweredApplicationName

        IF(@ApplicationId IS NULL)
        BEGIN
            SELECT  @ApplicationId = NEWID()
            INSERT  dbo.aspnet_Applications (ApplicationId, ApplicationName, LoweredApplicationName)
            VALUES  (@ApplicationId, @ApplicationName, LOWER(@ApplicationName))
        END


        IF( @TranStarted = 1 )
        BEGIN
            IF(@@ERROR = 0)
            BEGIN
	        SET @TranStarted = 0
	        COMMIT TRANSACTION
            END
            ELSE
            BEGIN
                SET @TranStarted = 0
                ROLLBACK TRANSACTION
            END
        END
    END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Roles_GetAllRoles]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Roles_GetAllRoles]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Roles_GetAllRoles] (
    @ApplicationName           nvarchar(256))
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN
    SELECT RoleName
    FROM   dbo.aspnet_Roles WHERE ApplicationId = @ApplicationId
    ORDER BY RoleName
END' 
END
GO
/****** Object:  View [dbo].[vw_aspnet_Applications]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[vw_aspnet_Applications]') AND OBJECTPROPERTY(id, N'IsView') = 1)
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vw_aspnet_Applications]
  AS SELECT [dbo].[aspnet_Applications].[ApplicationName], [dbo].[aspnet_Applications].[LoweredApplicationName], [dbo].[aspnet_Applications].[ApplicationId], [dbo].[aspnet_Applications].[Description]
  FROM [dbo].[aspnet_Applications]'
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_FindUsersByName]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_FindUsersByName]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_FindUsersByName]
    @ApplicationName       nvarchar(256),
    @UserNameToMatch       nvarchar(256),
    @PageIndex             int,
    @PageSize              int
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN 0

    -- Set the page bounds
    DECLARE @PageLowerBound int
    DECLARE @PageUpperBound int
    DECLARE @TotalRecords   int
    SET @PageLowerBound = @PageSize * (@PageIndex-1)
    SET @PageUpperBound = @PageSize - 1 + @PageLowerBound

    -- Create a temp table TO store the select results
    CREATE TABLE #PageIndexForUsers
    (
        IndexId int IDENTITY (0, 1) NOT NULL,
        UserId uniqueidentifier
    )

    -- Insert into our temp table
    INSERT INTO #PageIndexForUsers (UserId)
        SELECT u.UserId
        FROM   dbo.aspnet_Users u, dbo.aspnet_Membership m
        WHERE  u.ApplicationId = @ApplicationId AND m.UserId = u.UserId AND u.LoweredUserName LIKE LOWER(@UserNameToMatch)
        ORDER BY u.UserName


    SELECT  u.UserName, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
            m.CreateDate,
            m.LastLoginDate,
            u.LastActivityDate,
            m.LastPasswordChangedDate,
            u.UserId, m.IsLockedOut,
            m.LastLockoutDate
    FROM   dbo.aspnet_Membership m, dbo.aspnet_Users u, #PageIndexForUsers p
    WHERE  u.UserId = p.UserId AND u.UserId = m.UserId AND
           p.IndexId >= @PageLowerBound AND p.IndexId <= @PageUpperBound
    ORDER BY u.UserName

    SELECT  @TotalRecords = COUNT(*)
    FROM    #PageIndexForUsers
    RETURN @TotalRecords
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_FindUsersByEmail]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_FindUsersByEmail]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_FindUsersByEmail]
    @ApplicationName       nvarchar(256),
    @EmailToMatch          nvarchar(256),
    @PageIndex             int,
    @PageSize              int
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN 0

    -- Set the page bounds
    DECLARE @PageLowerBound int
    DECLARE @PageUpperBound int
    DECLARE @TotalRecords   int
    SET @PageLowerBound = @PageSize * (@PageIndex-1)
    SET @PageUpperBound = @PageSize - 1 + @PageLowerBound

    -- Create a temp table TO store the select results
    CREATE TABLE #PageIndexForUsers
    (
        IndexId int IDENTITY (0, 1) NOT NULL,
        UserId uniqueidentifier
    )

    -- Insert into our temp table
    IF( @EmailToMatch IS NULL )
        INSERT INTO #PageIndexForUsers (UserId)
            SELECT u.UserId
            FROM   dbo.aspnet_Users u, dbo.aspnet_Membership m
            WHERE  u.ApplicationId = @ApplicationId AND m.UserId = u.UserId AND m.Email IS NULL
            ORDER BY m.LoweredEmail
    ELSE
        INSERT INTO #PageIndexForUsers (UserId)
            SELECT u.UserId
            FROM   dbo.aspnet_Users u, dbo.aspnet_Membership m
            WHERE  u.ApplicationId = @ApplicationId AND m.UserId = u.UserId AND m.LoweredEmail LIKE LOWER(@EmailToMatch)
            ORDER BY m.LoweredEmail

    SELECT  u.UserName, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
            m.CreateDate,
            m.LastLoginDate,
            u.LastActivityDate,
            m.LastPasswordChangedDate,
            u.UserId, m.IsLockedOut,
            m.LastLockoutDate
    FROM   dbo.aspnet_Membership m, dbo.aspnet_Users u, #PageIndexForUsers p
    WHERE  u.UserId = p.UserId AND u.UserId = m.UserId AND
           p.IndexId >= @PageLowerBound AND p.IndexId <= @PageUpperBound
    ORDER BY m.LoweredEmail

    SELECT  @TotalRecords = COUNT(*)
    FROM    #PageIndexForUsers
    RETURN @TotalRecords
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_GetAllUsers]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_GetAllUsers]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_GetAllUsers]
    @ApplicationName       nvarchar(256),
    @PageIndex             int,
    @PageSize              int
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN 0


    -- Set the page bounds
    DECLARE @PageLowerBound int
    DECLARE @PageUpperBound int
    DECLARE @TotalRecords   int
    SET @PageLowerBound = @PageSize * (@PageIndex-1)
    SET @PageUpperBound = @PageSize - 1 + @PageLowerBound

    -- Create a temp table TO store the select results
    CREATE TABLE #PageIndexForUsers
    (
        IndexId int IDENTITY (0, 1) NOT NULL,
        UserId uniqueidentifier
    )

    -- Insert into our temp table
    INSERT INTO #PageIndexForUsers (UserId)
    SELECT u.UserId
    FROM   dbo.aspnet_Membership m, dbo.aspnet_Users u
    WHERE  u.ApplicationId = @ApplicationId AND u.UserId = m.UserId
    ORDER BY u.UserName

    SELECT @TotalRecords = @@ROWCOUNT

    SELECT u.UserName, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved,
            m.CreateDate,
            m.LastLoginDate,
            u.LastActivityDate,
            m.LastPasswordChangedDate,
            u.UserId, m.IsLockedOut,
            m.LastLockoutDate
    FROM   dbo.aspnet_Membership m, dbo.aspnet_Users u, #PageIndexForUsers p
    WHERE  u.UserId = p.UserId AND u.UserId = m.UserId AND
           p.IndexId >= @PageLowerBound AND p.IndexId <= @PageUpperBound
    ORDER BY u.UserName
    RETURN @TotalRecords
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Roles_RoleExists]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Roles_RoleExists]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Roles_RoleExists]
    @ApplicationName  nvarchar(256),
    @RoleName         nvarchar(256)
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL
    SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
    IF (@ApplicationId IS NULL)
        RETURN(0)
    IF (EXISTS (SELECT RoleName FROM dbo.aspnet_Roles WHERE LOWER(@RoleName) = LoweredRoleName AND ApplicationId = @ApplicationId ))
        RETURN(1)
    ELSE
        RETURN(0)
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Role_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Role_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[sp_Role_Get]
(
	@RoleId uniqueidentifier = null,
	@RoleName nvarchar(256) = null
	
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN	
	
	select RoleId, RoleName as [Name], r.Description
	from aspnet_Roles r
		inner join aspnet_Applications a on 
			r.ApplicationId = a.ApplicationId
	where
		((@RoleId is not null and r.RoleId = @RoleId ) or @RoleId is null ) and
		((@RoleName is not null and r.RoleName = @RoleName ) or @RoleName is null )

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_Hotkeywords_Log]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_Hotkeywords_Log]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[sp_cg_Hotkeywords_Log]
(
	@Keywords NVARCHAR(512),
	@IsMemberCreated BIT = 0,
	@UserId INT = 0,
	@SearchTime DateTime
)
AS
BEGIN
DECLARE @Frequency INT
SET @Frequency = 0
SELECT @Frequency =  Frequency  FROM Hishop_Hotkeywords ORDER BY Frequency 
IF EXISTS (SELECT Keywords FROM Hishop_Hotkeywords WHERE Lower(Keywords) = Lower(@Keywords))

	UPDATE
		Hishop_Hotkeywords
	SET
		Lasttime  = @SearchTime,
		Frequency = Frequency + 1
	WHERE
		Lower(Keywords) =Lower(@Keywords)
ELSE
	INSERT INTO Hishop_Hotkeywords(Keywords, SearchTime, Lasttime, IsMemberCreated, UserId, Frequency)
	VALUES (@Keywords, @SearchTime, @SearchTime, @IsMemberCreated, @UserId, @Frequency + 1 )
END


IF (SELECT COUNT(HID) FROM Hishop_Hotkeywords) > 50
DELETE FROM Hishop_Hotkeywords 
Where Hid NOT IN 
(SELECT TOP 50 HID FROM Hishop_HotKeyWords ORDER BY Frequency  DESC)' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_Hotkeyword_SwapDisplaySequence]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_Hotkeyword_SwapDisplaySequence]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_Hotkeyword_SwapDisplaySequence]
		(
		@Hid INT,
		@Hid2 INT
	)
AS
	
	DECLARE @DisplaySequence2 INT
	DECLARE @DisplaySequence INT
	
	SELECT @DisplaySequence = Frequency FROM Hishop_Hotkeywords WHERE Hid = @Hid
	SELECT @DisplaySequence2 = Frequency FROM Hishop_Hotkeywords WHERE Hid = @Hid2
	
	IF @DisplaySequence IS NULL OR @DisplaySequence2 IS NULL
		RETURN
	
	UPDATE Hishop_Hotkeywords SET Frequency = @DisplaySequence2 WHERE Hid = @Hid
	UPDATE Hishop_Hotkeywords SET Frequency = @DisplaySequence WHERE Hid = @Hid2' 
END
GO
/****** Object:  View [dbo].[vw_aspnet_Users]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[vw_aspnet_Users]') AND OBJECTPROPERTY(id, N'IsView') = 1)
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vw_aspnet_Users]
  AS SELECT [dbo].[aspnet_Users].[ApplicationId], [dbo].[aspnet_Users].[UserId], [dbo].[aspnet_Users].[UserName], [dbo].[aspnet_Users].[LoweredUserName], [dbo].[aspnet_Users].[MobileAlias], [dbo].[aspnet_Users].[IsAnonymous], [dbo].[aspnet_Users].[LastActivityDate]
  FROM [dbo].[aspnet_Users]'
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Users_CreateUser]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Users_CreateUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Users_CreateUser]
    @ApplicationId    uniqueidentifier,
    @UserName         nvarchar(256),
    @IsUserAnonymous  bit,
    @LastActivityDate DATETIME,
    @UserId           uniqueidentifier OUTPUT
AS
BEGIN
    IF( @UserId IS NULL )
        SELECT @UserId = NEWID()
    ELSE
    BEGIN
        IF( EXISTS( SELECT UserId FROM dbo.aspnet_Users
                    WHERE @UserId = UserId ) )
            RETURN -1
    END

    INSERT dbo.aspnet_Users (ApplicationId, UserId, UserName, LoweredUserName, IsAnonymous, LastActivityDate)
    VALUES (@ApplicationId, @UserId, @UserName, LOWER(@UserName), @IsUserAnonymous, @LastActivityDate)

    RETURN 0
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_Affiche_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_Affiche_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_Affiche_CreateUpdateDelete]
	(
		@AfficheId INT = NULL,
		@Title NVARCHAR(200) = NULL,
		@Content NTEXT = NULL,
		@AddedDate DATETIME= NULL,
		@UserId INT = NULL,
		@Action INT,
		@Status INT OUTPUT
	)
AS
	SET @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN
	
		DELETE FROM Hishop_Affiche WHERE AfficheId = @AfficheId
			
		IF @@ROWCOUNT > 0
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN

		INSERT INTO 
			Hishop_Affiche(Title, Content, AddedDate, UserId, IsMemberCreated)
		VALUES (@Title, @Content, @AddedDate, @UserId, 0)
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		 RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
		UPDATE Hishop_Affiche SET Title = @Title, AddedDate = @AddedDate, Content = @Content WHERE AfficheId = @AfficheId
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_HelpCategory_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_HelpCategory_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_HelpCategory_CreateUpdateDelete]
	(
		@CategoryId INT = NULL,
		@Name NVARCHAR(100) = NULL,
		@DisplaySequence INT = NULL,
		@IconUrl NVARCHAR(255) = NULL,
		@IndexChar CHAR(1) = NULL,
		@Description NVARCHAR(1000) = NULL,
		@IsShowFooter BIT = NULL,
		@Action INT,
		@Status INT OUTPUT
	)
AS	
    DECLARE @intErrorCode INT
	-- 初始化信息
	SELECT @Status = 99, @intErrorCode = 0
	
	IF @Action = 2 -- 删除
	BEGIN -- 同时删除分类下的文章
	
		SET XACT_ABORT ON
		
		BEGIN TRAN
		
		DELETE FROM Hishop_Helps WHERE CategoryId = @CategoryId
		SET @intErrorCode = @@ERROR
		
		IF @intErrorCode = 0
		BEGIN
			DELETE FROM Hishop_HelpCategories WHERE CategoryId = @CategoryId
				
			SET @intErrorCode = @@ERROR
		END
			
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
			COMMIT TRAN
		END
		ELSE
			ROLLBACK TRAN
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN
	
		--如果排序编号在此兄弟节点间存在,则修改分类中兄弟节点的其它的排序编号
		IF EXISTS(SELECT DisplaySequence FROM Hishop_HelpCategories WHERE DisplaySequence = @DisplaySequence) 
		-- 将大于或等于其兄弟节点的排序号加1
			UPDATE Hishop_HelpCategories SET DisplaySequence = DisplaySequence + 1 WHERE DisplaySequence >=@DisplaySequence
		
		INSERT INTO Hishop_HelpCategories ([Name], DisplaySequence, IconUrl, IndexChar, Description,IsShowFooter, UserId, IsMemberCreated)
		VALUES (@Name, @DisplaySequence, @IconUrl, @IndexChar, @Description,@IsShowFooter, 0, 0)
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
			--如果排序编号在此兄弟节点间存在,则修改分类中兄弟节点的其它的排序编号
		IF EXISTS(SELECT DisplaySequence FROM Hishop_HelpCategories WHERE DisplaySequence = @DisplaySequence AND CategoryId!=@CategoryId) 
		-- 将大于或等于其兄弟节点的排序号加1
			UPDATE Hishop_HelpCategories SET DisplaySequence = DisplaySequence + 1 WHERE DisplaySequence >=@DisplaySequence
			
		-- 修改分类信息
		UPDATE Hishop_HelpCategories SET [Name] = @Name, DisplaySequence = @DisplaySequence, IconUrl = @IconUrl, IndexChar = @IndexChar, Description = @Description, IsShowFooter = @IsShowFooter
		WHERE CategoryId = @CategoryId
		
		SET @intErrorCode = @intErrorCode + @@ERROR
		
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
		END
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_Help_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_Help_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_Help_CreateUpdateDelete]
  (
	    @CategoryId INT = NULL,
		@HelpId INT = NULL,
		@Title NVARCHAR(200) = NULL,
		@Description NVARCHAR(1000) = NULL,
		@Content NTEXT = NULL,
		@AddedDate DATETIME= NULL,
		@UserId INT = NULL,
		@IsShowFooter BIT = NULL,
		@Action INT,
		@Status INT OUTPUT
	)
AS
	SET @Status = 99
	
	IF @Action = 2 -- 删除
	BEGIN
	
		DELETE FROM Hishop_Helps WHERE HelpId = @HelpId
			
		IF @@ROWCOUNT > 0
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN

		INSERT INTO Hishop_Helps(CategoryId, Title, Description, Content, AddedDate, UserId, IsShowFooter, IsMemberCreated)
		VALUES (@CategoryId, @Title, @Description, @Content, @AddedDate, @UserId,@IsShowFooter, 0)
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
		UPDATE Hishop_Helps SET CategoryId = @CategoryId, AddedDate = @AddedDate, Title = @Title, Description = @Description, Content = @Content, IsShowFooter = @IsShowFooter
		WHERE HelpId = @HelpId
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_FriendlyLink_Sequence]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_FriendlyLink_Sequence]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_FriendlyLink_Sequence]
(
  @Sort INT , -- 是升 还是降 1 表示升 2表示降
  @LinkId INT
)
As 
    --  当前要修改的序号
	 DECLARE @oldSequence INT
	 -- 要修改成的序号
	 DECLARE @newSequence INT
	 -- 和当前对换的编号
	 DECLARE @newLinkId INT
 --升
 IF @Sort =1
    
 BEGIN
	
	 SELECT @oldSequence = DisplaySequence FROM [Hishop_FriendlyLinks]
     WHERE LinkId =@LinkId
 
     SELECT @newSequence = DisplaySequence FROM [Hishop_FriendlyLinks]
     WHERE LinkId =
		(SELECT TOP 1 LinkId FROM [Hishop_FriendlyLinks]
		WHERE DisplaySequence < @oldSequence
		Order by DisplaySequence DESC)

     SELECT @newLinkId = (SELECT TOP 1 LinkId FROM [Hishop_FriendlyLinks]
     WHERE DisplaySequence < @oldSequence
     ORDER BY DisplaySequence DESC)
    
    IF @newLinkId IS NOT NULL
     BEGIN
		  Update [Hishop_FriendlyLinks] SET DisplaySequence =@newSequence 
		  WHERE LinkId = @LinkId
     END
    IF @newLinkId IS NOT NULL
     BEGIN
		  Update [Hishop_FriendlyLinks] SET DisplaySequence = @oldSequence
		  WHERE LinkId = @newLinkId 
     END
  END 
 --降低
 IF @Sort =0
 BEGIN
	SELECT @oldSequence = DisplaySequence FROM [Hishop_FriendlyLinks]
	WHERE LinkId =@LinkId 
	 
	SELECT @newSequence = DisplaySequence FROM [Hishop_FriendlyLinks]
	WHERE LinkId =
		 (SELECT TOP 1 LinkId FROM [Hishop_FriendlyLinks]
		 WHERE DisplaySequence>@oldSequence 
		 Order by DisplaySequence ASC) 
	 
	SELECT @newLinkId = (SELECT TOP 1 LinkId FROM [Hishop_FriendlyLinks]
	WHERE DisplaySequence > @oldSequence 
	Order by DisplaySequence ASC)
    
    IF @newSequence IS NOT NULL
     BEGIN
		  UPDATE [Hishop_FriendlyLinks] SET DisplaySequence =@newSequence 
		  WHERE LinkId = @LinkId 
     END
    IF @newLinkId IS NOT NULL
     BEGIN
		  UPDATE [Hishop_FriendlyLinks] Set DisplaySequence = @oldSequence
		  WHERE LinkId =@newLinkId 
     END
 END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cg_FriendlyLink_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cg_FriendlyLink_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cg_FriendlyLink_CreateUpdateDelete]
	(
		@LinkId INT = NULL,
		@ImageUrl NVARCHAR(255) = NULL,
		@DisplaySequence INT = NULL,
		@LinkUrl NVARCHAR(255) = NULL,
		@Title NVARCHAR(100) = NULL,
		@Visible BIT = NULL,
		@Action INT,
		@UserId INT = 0,
		@IsMemberCreated BIT = 0,
		@Status INT OUTPUT
	)
AS	
    DECLARE @intErrorCode INT
	-- 初始化信息
	SELECT @Status = 99, @intErrorCode = 0
	
	IF @Action = 2 -- 删除
	BEGIN 
	
		SET XACT_ABORT ON
		
		BEGIN TRAN
		
		DELETE FROM Hishop_FriendlyLinks WHERE LinkId = @LinkId
		SET @intErrorCode = @@ERROR
			
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
			COMMIT TRAN
		END
		ELSE
			ROLLBACK TRAN
		
		RETURN
	END

	IF @Action = 0 -- 创建
	BEGIN
	
		--如果排序编号在此兄弟节点间存在,则修改分类中兄弟节点的其它的排序编号
		IF EXISTS(SELECT DisplaySequence FROM Hishop_FriendlyLinks WHERE DisplaySequence = @DisplaySequence) 
		-- 将大于或等于其兄弟节点的排序号加1
			UPDATE Hishop_FriendlyLinks SET DisplaySequence = DisplaySequence + 1 WHERE DisplaySequence >=@DisplaySequence
		
		INSERT INTO Hishop_FriendlyLinks
			([ImageUrl], DisplaySequence, LinkUrl, Title, Visible, UserId, IsMemberCreated)
		VALUES 
			(@ImageUrl, @DisplaySequence, @LinkUrl, @Title, @Visible, @UserId, @IsMemberCreated)
		
		IF @@ROWCOUNT = 1
			SET @Status = 0
		
		RETURN
	END

	IF @Action = 1 -- 修改
	BEGIN
		
			--如果排序编号在此兄弟节点间存在,则修改分类中兄弟节点的其它的排序编号
		IF EXISTS(SELECT DisplaySequence FROM Hishop_FriendlyLinks WHERE DisplaySequence = @DisplaySequence AND LinkId!=@LinkId) 
		-- 将大于或等于其兄弟节点的排序号加1
			UPDATE Hishop_FriendlyLinks SET DisplaySequence = DisplaySequence + 1 WHERE DisplaySequence >=@DisplaySequence
			
		-- 修改分类信息
		UPDATE 
			Hishop_FriendlyLinks 
		SET 
			[ImageUrl] = @ImageUrl,
			DisplaySequence = @DisplaySequence,
			LinkUrl = @LinkUrl,
			Title = @Title,
			Visible = @Visible

		WHERE LinkId = @LinkId
		
		SET @intErrorCode = @intErrorCode + @@ERROR
		
		IF @intErrorCode = 0
		BEGIN
			SET @Status = 0
		END
		
		RETURN
	END' 
END
GO
/****** Object:  View [dbo].[vw_aspnet_Roles]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[vw_aspnet_Roles]') AND OBJECTPROPERTY(id, N'IsView') = 1)
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[vw_aspnet_Roles]
  AS SELECT [dbo].[aspnet_Roles].[ApplicationId], [dbo].[aspnet_Roles].[RoleId], [dbo].[aspnet_Roles].[RoleName], [dbo].[aspnet_Roles].[LoweredRoleName], [dbo].[aspnet_Roles].[Description]
  FROM [dbo].[aspnet_Roles]'
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_ShippingAddress_CreateUpdateDelete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_ShippingAddress_CreateUpdateDelete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[sp_cf_ShippingAddress_CreateUpdateDelete]
(
   @RegionId	int = null,
   @ShippingId int= null,
   @UserId	int = null,
   @ShipTo	nvarchar(50) = null,
   @Address	nvarchar(500) = null,
   @Zipcode	nvarchar(20) = null,
   @EmailAddress	nvarchar(255) = null,	
   @TelPhone	nvarchar(20) = null,
   @CellPhone	nvarchar(20) = null,
   @Action INT,
   @Status INT OUTPUT
)
as 
  SET @Status = 99
  IF @Action = 2 -- 删除
  BEGIN 
     DELETE FROM Hishop_UserShippingAddresses
     WHERE  ShippingId = @ShippingId
     IF @@ROWCOUNT = 1
		    SET @Status = 0
     RETURN
  END
 
 IF @Action = 0 -- 创建
 BEGIN
   INSERT INTO Hishop_UserShippingAddresses(
     RegionId,UserId,ShipTo,Address,Zipcode,EmailAddress,TelPhone,CellPhone)
   VALUES(@RegionId,@UserId,@ShipTo,@Address,@Zipcode,
           @EmailAddress,@TelPhone,@CellPhone)
   IF @@ROWCOUNT = 1
			SET @Status = 0	
   RETURN
 END 
 
IF @Action = 1 --修改
 BEGIN 
  UPDATE Hishop_UserShippingAddresses
  set 
    RegionId = @RegionId,UserId= @UserId,ShipTo =@ShipTo,
    Address = @Address,Zipcode = @Zipcode,
    EmailAddress = @EmailAddress,TelPhone =@TelPhone,
    CellPhone = @CellPhone
    WHERE ShippingId = @ShippingId
   IF @@ROWCOUNT = 1
	 SET @Status = 0		
	RETURN
 END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_HelpCategory_Sequence]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_HelpCategory_Sequence]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_HelpCategory_Sequence]
(
  @Sort INT , -- 是升 还是降 1 表示升 2表示降
  @CategoryId INT
)
As 
    --  当前要修改的序号
	 DECLARE @oldSequence INT
	 -- 要修改成的序号
	 DECLARE @newSequence INT
	 -- 和当前对换的编号
	 DECLARE @newCategoryId INT
 --升
 IF @Sort =1
    
 BEGIN
	
	 SELECT @oldSequence = DisplaySequence FROM [Hishop_HelpCategories]
     WHERE CategoryId =@CategoryId
 
     SELECT @newSequence = DisplaySequence FROM [Hishop_HelpCategories]
     WHERE CategoryId =
		(SELECT TOP 1 CategoryId FROM [Hishop_HelpCategories]
		WHERE DisplaySequence < @oldSequence
		Order by DisplaySequence DESC)
     

     SELECT @newCategoryId = (SELECT TOP 1 CategoryId FROM [Hishop_HelpCategories]
     WHERE DisplaySequence < @oldSequence
     ORDER BY DisplaySequence DESC)
    
    IF @newCategoryId IS NOT NULL
     BEGIN
		  Update [Hishop_HelpCategories] SET DisplaySequence =@newSequence 
		  WHERE CategoryId = @CategoryId
     END
    IF @newCategoryId IS NOT NULL
     BEGIN
		  Update [Hishop_HelpCategories] SET DisplaySequence = @oldSequence
		  WHERE CategoryId = @newCategoryId
     END
  END 
 --降低
 IF @Sort =0
 BEGIN
	SELECT @oldSequence = DisplaySequence FROM [Hishop_HelpCategories]
	WHERE CategoryId =@CategoryId
	 
	SELECT @newSequence = DisplaySequence FROM [Hishop_HelpCategories]
	WHERE CategoryId =
		 (SELECT TOP 1 CategoryId FROM [Hishop_HelpCategories]
		 WHERE DisplaySequence>@oldSequence
		  Order by DisplaySequence ASC)
    
	 
	SELECT @newCategoryId = (SELECT TOP 1 CategoryId FROM [Hishop_HelpCategories]
	WHERE DisplaySequence > @oldSequence
	Order by DisplaySequence ASC)
    
    IF @newSequence IS NOT NULL
     BEGIN
		  UPDATE [Hishop_HelpCategories] SET DisplaySequence =@newSequence 
		  WHERE CategoryId = @CategoryId
     END
    IF @newCategoryId IS NOT NULL
     BEGIN
		  UPDATE [Hishop_HelpCategories] Set DisplaySequence = @oldSequence
		  WHERE CategoryId =@newCategoryId
     END
 END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cb_LeaveComments_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cb_LeaveComments_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cb_LeaveComments_Get]
(
	@PageIndex int,
	@PageSize int,
	@IsCount bit,
	@sqlPopulate ntext,
	@Total int = 0 output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * (@PageIndex - 1)
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	CREATE TABLE #PageIndexForSearch
	(
		IndexId INT IDENTITY (1, 1) NOT NULL,
		LeaveId BIGINT,
		IsReply bit
	)

	INSERT INTO #PageIndexForSearch (LeaveId,IsReply) 
    Exec sp_executesql @sqlPopulate
    
    SET @Total = @@rowcount
    
		-- 第一层
	SELECT l.*
	FROM 
	 Hishop_LeaveComments l ,#PageIndexForSearch
	WHERE 
		l.LeaveId = #PageIndexForSearch.LeaveId AND
		#PageIndexForSearch.IndexId > @PageLowerBound AND
		#PageIndexForSearch.IndexId < @PageUpperBound
	ORDER BY
		#PageIndexForSearch.IndexId

	-- 第二层
	SELECT r.*,
	    (select UserName from vw_Users_FullUser where hi_UserId=r.UserId) as ReplyUserName
		FROM Hishop_LeaveCommentReplys r
		order by ReplyDate desc

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cf_BalanceDraw_Request]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cf_BalanceDraw_Request]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cf_BalanceDraw_Request]
(
	@RequestTime DateTime, 
	@Amount money,
	@Applicant int,
	@RequestStatus int,
	@MerchantCode nvarchar(1000),
	@Remark nvarchar(2000),
	@Status INT OUTPUT
	)
AS
	SET @Status = 99	
	BEGIN
		SET XACT_ABORT ON
		DECLARE @intErrorCode INT
		
		BEGIN TRAN
		-- 添加一条提现申请的记录	
		INSERT INTO Hishop_BalanceDrawRequest VALUES(@RequestTime,@Amount,@Applicant,@RequestStatus,@MerchantCode,@Remark)
		SET @intErrorCode = @@RowCount
		
		IF @intErrorCode = 1
		-- 添加一条冻结金额明细
		INSERT INTO Hishop_BalanceFreezeDetails VALUES(1,@RequestTime,@Amount,@Applicant,@Remark)	
		SET @intErrorCode = @intErrorCode + @@RowCount
					
		IF @intErrorCode = 2
		BEGIN
			SET @Status = 0
			COMMIT TRAN
		END
		ELSE
			ROLLBACK TRAN
			
		RETURN
	END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_cd_ShoppingCartProducts_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_cd_ShoppingCartProducts_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_cd_ShoppingCartProducts_Get]
(
	@UserId INT,
	@Skus nvarchar(4000)
)
AS
	CREATE TABLE #skuTable (SKU nvarchar(50))
	DECLARE @UserRank INT
	
	INSERT INTO #skuTable(SKU) SELECT UnitString FROM F_SplitToString(@Skus, '','')
	SELECT @UserRank = UserRank FROM Hishop_UserProfile WHERE UserId = @UserId
	
	IF (@UserRank IS NULL)
		SELECT 
			s.SKU, s.ProductId, s.Stock, ISNULL(s.Price, 0.00) AS SKUPrice, s.AttributeNames, s.AttributeValues, 
			p.ThumbnailsUrl, p.ProductName, ISNULL(p.CostPrice, 0.00) AS CostPrice, p.SalePrice, p.Weight, p.QuantityLimit, p.MinQuantity
		FROM
			Hishop_SKUs s INNER JOIN #skuTable ON s.SKU = #skuTable.SKU
			INNER JOIN Hishop_Products p ON s.ProductId = p.ProductId
			
	ELSE
		SELECT 
			s.SKU, s.ProductId, s.Stock, ISNULL(s.Price, 0.00) AS SKUPrice, s.AttributeNames, s.AttributeValues, 
			p.ThumbnailsUrl, p.ProductName, ISNULL(p.CostPrice, 0.00) AS CostPrice, ISNULL(pp.SalePrice, p.SalePrice) AS SalePrice, p.Weight, p.QuantityLimit, p.MinQuantity
		FROM
			Hishop_SKUs s INNER JOIN #skuTable ON s.SKU = #skuTable.SKU
			INNER JOIN Hishop_Products p ON s.ProductId = p.ProductId
			LEFT OUTER JOIN Hishop_ProductPrices pp ON p.ProductId = pp.ProductId AND pp.RankId = @UserRank
			
		DROP TABLE #skuTable' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_co_AgentOrderTakePercentage_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_co_AgentOrderTakePercentage_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_co_AgentOrderTakePercentage_Get]
(
	@UserId INT,
	@AgetnId INT,
	@ProductId nvarchar(4000)
)
AS
	CREATE TABLE #ProcutIdTable(ProcutId nvarchar(50))
	DECLARE @UserRank INT
	DECLARE @AgentRank INT
	DECLARE @Price INT
	DECLARE @AgentPrice INT
	
	INSERT INTO #ProcutIdTable(ProcutId) SELECT UnitString FROM F_SplitToString(@ProductId, '','')
	SELECT @UserRank = UserRank FROM Hishop_UserProfile WHERE UserId = @UserId
	SELECT @AgentRank = UserRank FROM Hishop_UserProfile WHERE UserId = @AgetnId

    -- 获取会员订单总价格
	SELECT 
		@Price = SUM(ISNULL(pp.SalePrice, p.SalePrice))
	FROM
		Hishop_Products p INNER JOIN #ProcutIdTable ON p.ProductId = #ProcutIdTable.ProductId
		LEFT OUTER JOIN Hishop_ProductPrices pp ON p.ProductId = pp.ProductId
	WHERE
		pp.RankId = @UserRank
		
	-- 获取代理订单总价格	
	SELECT 
		@AgentPrice = SUM(ISNULL(pp.SalePrice, p.SalePrice))
	FROM
		Hishop_Products p INNER JOIN #ProcutIdTable ON p.ProductId = #ProcutIdTable.ProductId
		LEFT OUTER JOIN Hishop_ProductPrices pp ON p.ProductId = pp.ProductId
	WHERE
		pp.RankId = @UserRank
		
	SELECT (@Price - @AgentPrice)	
		
	DROP TABLE #ProcutIdTable' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_OrderOptionItem_Add]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_OrderOptionItem_Add]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_OrderOptionItem_Add]
(
  @OrderId	nvarchar(50) = null,
  @LookupListId	int	=null,
  @LookupItemId	int	=null,
  @ListDescription nvarchar(500) =null,
  @ItemDescription nvarchar(500) = null,
  @AdjustedPrice	money=null,
  @CustomerTitle	nvarchar(500)=null,
  @CustomerDescription	nvarchar(50)=null
)
as
 
  INSERT INTO 
   Hishop_OrderOptions (OrderId,LookupListId,LookupItemId,ListDescription,
   ItemDescription,AdjustedPrice,CustomerTitle,CustomerDescription)
  VALUES
   (@OrderId,@LookupListId,@LookupItemId,@ListDescription,
   @ItemDescription,@AdjustedPrice,@CustomerTitle,@CustomerDescription)' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Emails_Enqueue]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Emails_Enqueue]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE  PROCEDURE [dbo].[sp_Emails_Enqueue]
(
	@EmailTo	nvarchar(2000),
	@EmailCc	ntext,
	@EmailBcc	ntext,
	@EmailFrom	nvarchar(256),
	@EmailSubject	nvarchar(1024),
	@EmailBody	ntext,
	@EmailPriority	int,
	@IsBodyHtml bit
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	INSERT INTO
		Hishop_EmailQueue
		(
			emailTo,
			emailCc,
			emailBcc,
			EmailFrom,
			EmailSubject,
			EmailBody,
			emailPriority,
			IsBodyHtml
		)
	VALUES
		(
			@EmailTo,
			@EmailCc,
			@EmailBcc,
			@EmailFrom,
			@EmailSubject,
			@EmailBody,
			@EmailPriority,
			@IsBodyHtml
		)		
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_Emails_Dequeue]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_Emails_Dequeue]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE    PROCEDURE [dbo].[sp_Emails_Dequeue]

AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	SELECT * FROM Hishop_EmailQueue Where NextTryTime < getdate()
	
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_EmailQueue_Failure]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_EmailQueue_Failure]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE proc [dbo].[sp_EmailQueue_Failure]
	@EmailId uniqueidentifier,
	@FailureInterval int,
	@MaxNumberOfTries int
as
SET Transaction Isolation Level Read UNCOMMITTED
declare @NumberOfTries int
select @NumberOfTries = NumberOfTries + 1 from Hishop_EmailQueue where EmailId = @EmailId

if @NumberOfTries <= @MaxNumberOfTries
begin
	update Hishop_EmailQueue set
		NumberOfTries = @NumberOfTries,
		NextTryTime = dateadd(minute, @NumberOfTries * @FailureInterval, getdate())
	where EmailId = @EmailId
end
else
begin
	delete from Hishop_EmailQueue where EmailId = @EmailId
end' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_EmailQueue_Delete]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_EmailQueue_Delete]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE proc [dbo].[sp_EmailQueue_Delete]
	@EmailId uniqueidentifier 
as
SET Transaction Isolation Level Read UNCOMMITTED
	delete from Hishop_EmailQueue where EmailId = @EmailId' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_SiteSettings_Save]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_SiteSettings_Save]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE procedure [dbo].[sp_SiteSettings_Save]
(
	@Disabled		smallint,
	@SettingsXML	 	ntext = null,
	@ApplicationName	nvarchar(256)
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	UPDATE
		Hishop_SiteSettings
	SET
		Disabled = @Disabled,
		SettingsXML = @SettingsXML,
		ApplicationName = @ApplicationName		
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_SiteSettings_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_SiteSettings_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_SiteSettings_Get]

AS
	SET Transaction Isolation Level Read UNCOMMITTED

	Select TOP 1
		ss.SettingsXML, ss.Disabled, ss.Version, 
		ss.SettingsKey, ss.ApplicationName, ss.SettingsID 
	FROM 
		Hishop_SiteSettings ss
	ORDER BY ss.SettingsID' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Roles_CreateRole]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Roles_CreateRole]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Roles_CreateRole]
    @ApplicationName  nvarchar(256),
    @RoleName         nvarchar(256)
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL

    DECLARE @ErrorCode     int
    SET @ErrorCode = 0

    DECLARE @TranStarted   bit
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
        SET @TranStarted = 0

    EXEC dbo.aspnet_Applications_CreateApplication @ApplicationName, @ApplicationId OUTPUT

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (EXISTS(SELECT RoleId FROM dbo.aspnet_Roles WHERE LoweredRoleName = LOWER(@RoleName) AND ApplicationId = @ApplicationId))
    BEGIN
        SET @ErrorCode = 1
        GOTO Cleanup
    END

    INSERT INTO dbo.aspnet_Roles
                (ApplicationId, RoleName, LoweredRoleName)
         VALUES (@ApplicationId, @RoleName, LOWER(@RoleName))

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        COMMIT TRANSACTION
    END

    RETURN(0)

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
        ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_System_CreateShop]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_System_CreateShop]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE Proc [dbo].[sp_System_CreateShop]
(
	@ApplicationName nvarchar(512),
	@AdminEmail nvarchar(256),
	@AdminUserName nvarchar(256),
	@AdminPassword nvarchar(256),
	@PasswordFormat int = 0,	-- 0 = clear text, 1 = encrypted
	@DefaultCurrencyCode nvarchar(20),
	@DefaultCurrencyName nvarchar(20),
	@DefaultCurrencySymbol nvarchar(20),
	@Status INT = 0 OUTPUT
)

as

-- 如已经存在站点，则不执行创建操作
IF (SELECT Count(SettingsId) FROM Hishop_SiteSettings) > 0
	RETURN

SELECT @Status = 0
-- 设置如果任何地方执行错误，则回滚整个事务
SET XACT_ABORT ON

--We must have both these values to continue
if(@ApplicationName is  null)
BEGIN
	Select @Status = -1
	RETURN
END

Declare @ApplicationID uniqueidentifier
Declare @AdminUserID uniqueidentifier
DECLARE @Version nvarchar(64)
DECLARE @AdminRoleID uniqueidentifier

Set @Version = null

--Get or Create the Application ID.
--An ApplicationName/ID can exist in more than one site, so it does not need to be unique
Set @ApplicationID = null
Select @ApplicationID = ApplicationId FROM aspnet_Applications where  LoweredApplicationName = Lower(@ApplicationName)

BEGIN TRAN

if(@ApplicationID is null)
BEGIN
	-- 如果应用程序还不存在，则创建
	exec aspnet_Applications_CreateApplication @ApplicationName, @ApplicationId = @ApplicationID OUTPUT
END
ELSE
BEGIN
	-- 如果应用程序已经存在，则返回
	SELECT @Status = -3
	
	ROLLBACK TRAN
	RETURN
END

--Insert a record into the SiteSettings table
INSERT Hishop_SiteSettings (Disabled, Version, SettingsKey, ApplicationName)
VALUES (0,@Version,newID(),@ApplicationName)

-- Created default roles...

declare @EveryoneRoleID uniqueidentifier

Set @EveryoneRoleID = newID()


INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (@EveryoneRoleID, @ApplicationID, N''Everyone'', N''everyone'', N''Do not add users to this role. This role exists only for permission mapping. All anonymous and registered users are automatically part of this role.'')
INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N''Registered Users'', N''registered users'', N''Users who create accounts are automatically added to this role.'')
INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N''SystemAdministrator'', N''systemadministrator'', N''Site Administration role.'')
INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N''Manager'', N''manager'', N'''')

Declare @UserID uniqueidentifier
Declare @hi_UserId int

if(@AdminUserName is not null)
Begin

	Set @UserID = newid()
	
	-- Create Admin User
	INSERT INTO [aspnet_Users] ([UserId], [ApplicationId], [UserName], [LoweredUserName], [MobileAlias], [IsAnonymous], [LastActivityDate]) 
	      VALUES (@UserID, @ApplicationID, @AdminUserName, Lower(@AdminUserName), NULL, 0, getdate())
	--Do we need to make Salt configurable?
	INSERT INTO [aspnet_Membership] ([ApplicationId], [UserId], [Password],     [PasswordFormat], [PasswordSalt],              [MobilePIN], [Email], [LoweredEmail], [PasswordQuestion], [PasswordAnswer], [IsApproved], [CreateDate], [LastLoginDate], [LastPasswordChangedDate], [Comment], FailedPasswordAnswerAttemptWindowStart, FailedPasswordAnswerAttemptCount, FailedPasswordAttemptWindowStart, FailedPasswordAttemptCount, LastLockoutDate, IsLockedOut) 
				 VALUES (@ApplicationID, @UserID,  @AdminPassword, @PasswordFormat,   N''DVZTktxeMzDtXR7eik7Cdw=='', NULL,       @AdminEmail,    NULL,            NULL,               NULL,            1,            getdate(),    getdate(),       getdate(),                 NULL,                 ''1753-01-01'',                              0,                               ''1753-01-01'',                       0,                          ''1753-01-01'',      0)
	
	INSERT INTO [Hishop_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction])
	VALUES(@UserID, 0,1, null, getdate(), '''')


	Set @hi_UserId = @@Identity
	
	INSERT INTO [Hishop_UserProfile]([UserID], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableHtmlEmail], [MembershipID], [PropertyNames], [PropertyValues])
	VALUES (@hi_UserId, 1, 0, 1, 0, @UserID, NULL, NULL)
	
	Insert aspnet_UsersInRoles (UserId, RoleId) 
	Select @UserID, RoleId FROM aspnet_Roles where ApplicationId = @ApplicationID

End


Set @UserID = newid()

--Create Anonymous User
INSERT INTO [aspnet_Users] ([UserId], [ApplicationId], [UserName], [LoweredUserName], [MobileAlias], [IsAnonymous], [LastActivityDate]) 
      VALUES (@UserID, @ApplicationID, ''Anonymous'', Lower(''Anonymous''), NULL, 1, getdate())
--Do we need to make Salt configurable?
INSERT INTO [aspnet_Membership] ([ApplicationId],[UserId], [Password],     [PasswordFormat], [PasswordSalt],              [MobilePIN], [Email],						[LoweredEmail], [PasswordQuestion], [PasswordAnswer], [IsApproved], [CreateDate], [LastLoginDate], [LastPasswordChangedDate], [Comment],	[FailedPasswordAnswerAttemptWindowStart], [FailedPasswordAnswerAttemptCount],	[FailedPasswordAttemptWindowStart], [FailedPasswordAttemptCount],	[LastLockoutDate],	[IsLockedOut])
                         VALUES (@ApplicationID, @UserID,  @UserID,         0,               N''DVZTktxeMzDtXR7eik7Cdw=='', NULL,        ''anonymous@localhost.com'',    NULL,            NULL,               NULL,            1,            getdate(),    getdate(),       getdate(),                 NULL,			''1753-01-01'',                              0,									''1753-01-01'',                       0,								''1753-01-01'',		0)

INSERT INTO [Hishop_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction])
VALUES(@UserID, 0,1, null, getdate(), '''')

Set @hi_UserId = @@Identity

INSERT INTO [Hishop_UserProfile]([UserID], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableHtmlEmail], [MembershipID], [PropertyNames], [PropertyValues])
VALUES                          (@hi_UserId, 0, 0, 1, 0, @UserID, NULL, NULL)

-- add the anonymous user to the everyone role
INSERT INTO aspnet_UsersInRoles ([UserId], [RoleId]) VALUES( @UserID, @EveryoneRoleID )

-- 添加默认货币
INSERT INTO Hishop_Currencys(Code, [Name], Symbol, ExchangeRate)
VALUES(@DefaultCurrencyCode, @DefaultCurrencyName, @DefaultCurrencySymbol, 1)

COMMIT TRAN' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Membership_CreateUser]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Membership_CreateUser]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Membership_CreateUser]
    @ApplicationName                        nvarchar(256),
    @UserName                               nvarchar(256),
    @Password                               nvarchar(128),
    @PasswordSalt                           nvarchar(128),
    @Email                                  nvarchar(256),
    @PasswordQuestion                       nvarchar(256),
    @PasswordAnswer                         nvarchar(128),
    @IsApproved                             bit,
    @CurrentTimeUtc                         datetime,
    @CreateDate                             datetime = NULL,
    @UniqueEmail                            int      = 0,
    @PasswordFormat                         int      = 0,
    @UserId                                 uniqueidentifier OUTPUT
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL

    DECLARE @NewUserId uniqueidentifier
    SELECT @NewUserId = NULL

    DECLARE @IsLockedOut bit
    SET @IsLockedOut = 0

    DECLARE @LastLockoutDate  datetime
    SET @LastLockoutDate = CONVERT( datetime, ''17540101'', 112 )

    DECLARE @FailedPasswordAttemptCount int
    SET @FailedPasswordAttemptCount = 0

    DECLARE @FailedPasswordAttemptWindowStart  datetime
    SET @FailedPasswordAttemptWindowStart = CONVERT( datetime, ''17540101'', 112 )

    DECLARE @FailedPasswordAnswerAttemptCount int
    SET @FailedPasswordAnswerAttemptCount = 0

    DECLARE @FailedPasswordAnswerAttemptWindowStart  datetime
    SET @FailedPasswordAnswerAttemptWindowStart = CONVERT( datetime, ''17540101'', 112 )

    DECLARE @NewUserCreated bit
    DECLARE @ReturnValue   int
    SET @ReturnValue = 0

    DECLARE @ErrorCode     int
    SET @ErrorCode = 0

    DECLARE @TranStarted   bit
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
	    BEGIN TRANSACTION
	    SET @TranStarted = 1
    END
    ELSE
    	SET @TranStarted = 0

    EXEC dbo.aspnet_Applications_CreateApplication @ApplicationName, @ApplicationId OUTPUT

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    SET @CreateDate = @CurrentTimeUtc

    SELECT  @NewUserId = UserId FROM dbo.aspnet_Users WHERE LOWER(@UserName) = LoweredUserName AND @ApplicationId = ApplicationId
    IF ( @NewUserId IS NULL )
    BEGIN
        SET @NewUserId = @UserId
        EXEC @ReturnValue = dbo.aspnet_Users_CreateUser @ApplicationId, @UserName, 0, @CreateDate, @NewUserId OUTPUT
        SET @NewUserCreated = 1
    END
    ELSE
    BEGIN
        SET @NewUserCreated = 0
        IF( @NewUserId <> @UserId AND @UserId IS NOT NULL )
        BEGIN
            SET @ErrorCode = 6
            GOTO Cleanup
        END
    END

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF( @ReturnValue = -1 )
    BEGIN
        SET @ErrorCode = 10
        GOTO Cleanup
    END

    IF ( EXISTS ( SELECT UserId
                  FROM   dbo.aspnet_Membership
                  WHERE  @NewUserId = UserId ) )
    BEGIN
        SET @ErrorCode = 6
        GOTO Cleanup
    END

    SET @UserId = @NewUserId

    IF (@UniqueEmail = 1)
    BEGIN
        IF (EXISTS (SELECT *
                    FROM  dbo.aspnet_Membership m WITH ( UPDLOCK, HOLDLOCK )
                    WHERE ApplicationId = @ApplicationId AND LoweredEmail = LOWER(@Email)))
        BEGIN
            SET @ErrorCode = 7
            GOTO Cleanup
        END
    END

    IF (@NewUserCreated = 0)
    BEGIN
        UPDATE dbo.aspnet_Users
        SET    LastActivityDate = @CreateDate
        WHERE  @UserId = UserId
        IF( @@ERROR <> 0 )
        BEGIN
            SET @ErrorCode = -1
            GOTO Cleanup
        END
    END

    INSERT INTO dbo.aspnet_Membership
                ( ApplicationId,
                  UserId,
                  Password,
                  PasswordSalt,
                  Email,
                  LoweredEmail,
                  PasswordQuestion,
                  PasswordAnswer,
                  PasswordFormat,
                  IsApproved,
                  IsLockedOut,
                  CreateDate,
                  LastLoginDate,
                  LastPasswordChangedDate,
                  LastLockoutDate,
                  FailedPasswordAttemptCount,
                  FailedPasswordAttemptWindowStart,
                  FailedPasswordAnswerAttemptCount,
                  FailedPasswordAnswerAttemptWindowStart )
         VALUES ( @ApplicationId,
                  @UserId,
                  @Password,
                  @PasswordSalt,
                  @Email,
                  LOWER(@Email),
                  @PasswordQuestion,
                  @PasswordAnswer,
                  @PasswordFormat,
                  @IsApproved,
                  @IsLockedOut,
                  @CreateDate,
                  @CreateDate,
                  @CreateDate,
                  @LastLockoutDate,
                  @FailedPasswordAttemptCount,
                  @FailedPasswordAttemptWindowStart,
                  @FailedPasswordAnswerAttemptCount,
                  @FailedPasswordAnswerAttemptWindowStart )

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF( @TranStarted = 1 )
    BEGIN
	    SET @TranStarted = 0
	    COMMIT TRANSACTION
    END

    RETURN 0

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Profile_SetProperties]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Profile_SetProperties]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Profile_SetProperties]
    @ApplicationName        nvarchar(256),
    @PropertyNames          ntext,
    @PropertyValuesString   ntext,
    @PropertyValuesBinary   image,
    @UserName               nvarchar(256),
    @IsUserAnonymous        bit,
    @CurrentTimeUtc         datetime
AS
BEGIN
    DECLARE @ApplicationId uniqueidentifier
    SELECT  @ApplicationId = NULL

    DECLARE @ErrorCode     int
    SET @ErrorCode = 0

    DECLARE @TranStarted   bit
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
       BEGIN TRANSACTION
       SET @TranStarted = 1
    END
    ELSE
    	SET @TranStarted = 0

    EXEC dbo.aspnet_Applications_CreateApplication @ApplicationName, @ApplicationId OUTPUT

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    DECLARE @UserId uniqueidentifier
    DECLARE @LastActivityDate datetime
    SELECT  @UserId = NULL
    SELECT  @LastActivityDate = @CurrentTimeUtc

    SELECT @UserId = UserId
    FROM   dbo.aspnet_Users
    WHERE  ApplicationId = @ApplicationId AND LoweredUserName = LOWER(@UserName)
    IF (@UserId IS NULL)
        EXEC dbo.aspnet_Users_CreateUser @ApplicationId, @UserName, @IsUserAnonymous, @LastActivityDate, @UserId OUTPUT

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    UPDATE dbo.aspnet_Users
    SET    LastActivityDate=@CurrentTimeUtc
    WHERE  UserId = @UserId

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF (EXISTS( SELECT *
               FROM   dbo.aspnet_Profile
               WHERE  UserId = @UserId))
        UPDATE dbo.aspnet_Profile
        SET    PropertyNames=@PropertyNames, PropertyValuesString = @PropertyValuesString,
               PropertyValuesBinary = @PropertyValuesBinary, LastUpdatedDate=@CurrentTimeUtc
        WHERE  UserId = @UserId
    ELSE
        INSERT INTO dbo.aspnet_Profile(UserId, PropertyNames, PropertyValuesString, PropertyValuesBinary, LastUpdatedDate)
             VALUES (@UserId, @PropertyNames, @PropertyValuesString, @PropertyValuesBinary, @CurrentTimeUtc)

    IF( @@ERROR <> 0 )
    BEGIN
        SET @ErrorCode = -1
        GOTO Cleanup
    END

    IF( @TranStarted = 1 )
    BEGIN
    	SET @TranStarted = 0
    	COMMIT TRANSACTION
    END

    RETURN 0

Cleanup:

    IF( @TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END

    RETURN @ErrorCode

END' 
END
GO
/****** Object:  StoredProcedure [dbo].[sp_user_Get]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[sp_user_Get]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[sp_user_Get]
(
	@UserId int,
	@Username nvarchar(64) = null,
	@IsOnline bit = 0,
	@LastAction nvarchar(1024) = ''''
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @UserIDGUID as uniqueidentifier

	
	-- Are we looking up the user by username or ID?
	IF @Username is not null
	BEGIN
		
		SELECT
			@UserIDGUID = U.UserId
		FROM
			aspnet_Users U,
			Hishop_SiteSettings S,
			aspnet_Applications A
		WHERE
			A.ApplicationName = S.ApplicationName AND
			A.ApplicationId = U.ApplicationId AND
			U.UserName = @Username

		SELECT
			@UserID = UserID
		FROM
			Hishop_Users M
		WHERE
			M.MembershipId = @UserIDGUID AND M.Deleted = 0

		SELECT
			U.*
		FROM
			vw_Users_FullUser U (nolock)
		WHERE 
			UserId = @UserIDGUID


	END
	ELSE BEGIN
		-- Looking up the user by ID
		
		if(@UserId = 0)
		Begin
			exec sp_GetAnonymousUserID @UserId output
		End
	
		-- Get the user details
		SELECT
			U.*
		FROM 
			vw_Users_FullUser U (nolock)
		WHERE 
			U.hi_UserId = @UserId
	END

	IF @IsOnline = 1
	BEGIN
		EXEC sp_system_UserIsOnline @UserId, @LastAction
	END
END' 
END
GO
/****** Object:  StoredProcedure [dbo].[aspnet_Profile_DeleteProfiles]    Script Date: 04/20/2009 16:21:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[aspnet_Profile_DeleteProfiles]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
BEGIN
EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[aspnet_Profile_DeleteProfiles]
    @ApplicationName        nvarchar(256),
    @UserNames              nvarchar(4000)
AS
BEGIN
    DECLARE @UserName     nvarchar(256)
    DECLARE @CurrentPos   int
    DECLARE @NextPos      int
    DECLARE @NumDeleted   int
    DECLARE @DeletedUser  int
    DECLARE @TranStarted  bit
    DECLARE @ErrorCode    int

    SET @ErrorCode = 0
    SET @CurrentPos = 1
    SET @NumDeleted = 0
    SET @TranStarted = 0

    IF( @@TRANCOUNT = 0 )
    BEGIN
        BEGIN TRANSACTION
        SET @TranStarted = 1
    END
    ELSE
    	SET @TranStarted = 0

    WHILE (@CurrentPos <= LEN(@UserNames))
    BEGIN
        SELECT @NextPos = CHARINDEX(N'','', @UserNames,  @CurrentPos)
        IF (@NextPos = 0 OR @NextPos IS NULL)
            SELECT @NextPos = LEN(@UserNames) + 1

        SELECT @UserName = SUBSTRING(@UserNames, @CurrentPos, @NextPos - @CurrentPos)
        SELECT @CurrentPos = @NextPos+1

        IF (LEN(@UserName) > 0)
        BEGIN
            SELECT @DeletedUser = 0
            EXEC dbo.aspnet_Users_DeleteUser @ApplicationName, @UserName, 4, @DeletedUser OUTPUT
            IF( @@ERROR <> 0 )
            BEGIN
                SET @ErrorCode = -1
                GOTO Cleanup
            END
            IF (@DeletedUser <> 0)
                SELECT @NumDeleted = @NumDeleted + 1
        END
    END
    SELECT @NumDeleted
    IF (@TranStarted = 1)
    BEGIN
    	SET @TranStarted = 0
    	COMMIT TRANSACTION
    END
    SET @TranStarted = 0

    RETURN 0

Cleanup:
    IF (@TranStarted = 1 )
    BEGIN
        SET @TranStarted = 0
    	ROLLBACK TRANSACTION
    END
    RETURN @ErrorCode
END' 
END
GO
/****** Object:  Default [DF__aspnet_Ap__Appli__7B905C75]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__aspnet_Ap__Appli__7B905C75]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__aspnet_Ap__Appli__7B905C75]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[aspnet_Applications] ADD  CONSTRAINT [DF__aspnet_Ap__Appli__7B905C75]  DEFAULT (newid()) FOR [ApplicationId]
END


END
GO
/****** Object:  Default [DF__aspnet_Me__Passw__108B795B]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__aspnet_Me__Passw__108B795B]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__aspnet_Me__Passw__108B795B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[aspnet_Membership] ADD  CONSTRAINT [DF__aspnet_Me__Passw__108B795B]  DEFAULT ((0)) FOR [PasswordFormat]
END


END
GO
/****** Object:  Default [DF__aspnet_Ro__RoleI__2E1BDC42]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__aspnet_Ro__RoleI__2E1BDC42]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__aspnet_Ro__RoleI__2E1BDC42]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[aspnet_Roles] ADD  CONSTRAINT [DF__aspnet_Ro__RoleI__2E1BDC42]  DEFAULT (newid()) FOR [RoleId]
END


END
GO
/****** Object:  Default [DF__aspnet_Us__UserI__7F60ED59]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__aspnet_Us__UserI__7F60ED59]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__aspnet_Us__UserI__7F60ED59]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[aspnet_Users] ADD  CONSTRAINT [DF__aspnet_Us__UserI__7F60ED59]  DEFAULT (newid()) FOR [UserId]
END


END
GO
/****** Object:  Default [DF__aspnet_Us__Mobil__00551192]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__aspnet_Us__Mobil__00551192]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__aspnet_Us__Mobil__00551192]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[aspnet_Users] ADD  CONSTRAINT [DF__aspnet_Us__Mobil__00551192]  DEFAULT (NULL) FOR [MobileAlias]
END


END
GO
/****** Object:  Default [DF__aspnet_Us__IsAno__014935CB]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__aspnet_Us__IsAno__014935CB]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__aspnet_Us__IsAno__014935CB]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[aspnet_Users] ADD  CONSTRAINT [DF__aspnet_Us__IsAno__014935CB]  DEFAULT ((0)) FOR [IsAnonymous]
END


END
GO
/****** Object:  Default [DF_Hishop_EmailQueue_EmailID]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_EmailQueue_EmailID]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_EmailQueue_EmailID]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_EmailQueue] ADD  CONSTRAINT [DF_Hishop_EmailQueue_EmailID]  DEFAULT (newid()) FOR [EmailId]
END


END
GO
/****** Object:  Default [DF_Hishop_EmailQueue_NextTryTime]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_EmailQueue_NextTryTime]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_EmailQueue_NextTryTime]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_EmailQueue] ADD  CONSTRAINT [DF_Hishop_EmailQueue_NextTryTime]  DEFAULT ('1/1/1979 12:00:00') FOR [NextTryTime]
END


END
GO
/****** Object:  Default [DF_Hishop_EmailQueue_NumberOfTries]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_EmailQueue_NumberOfTries]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_EmailQueue_NumberOfTries]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_EmailQueue] ADD  CONSTRAINT [DF_Hishop_EmailQueue_NumberOfTries]  DEFAULT ((0)) FOR [NumberOfTries]
END


END
GO
/****** Object:  Default [DF_Hishop_Products_Recommended]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_Products_Recommended]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_Products_Recommended]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_Products] ADD  CONSTRAINT [DF_Hishop_Products_Recommended]  DEFAULT ((0)) FOR [Recommended]
END


END
GO
/****** Object:  Default [DF_Hishop_Products_Latest]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_Products_Latest]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_Products_Latest]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_Products] ADD  CONSTRAINT [DF_Hishop_Products_Latest]  DEFAULT ((1)) FOR [Latest]
END


END
GO
/****** Object:  Default [DF_Hishop_Products_Hotsale]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_Products_Hotsale]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_Products_Hotsale]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_Products] ADD  CONSTRAINT [DF_Hishop_Products_Hotsale]  DEFAULT ((0)) FOR [Hotsale]
END


END
GO
/****** Object:  Default [DF_Hishop_Products_SpecialOffer]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_Products_SpecialOffer]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_Products_SpecialOffer]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_Products] ADD  CONSTRAINT [DF_Hishop_Products_SpecialOffer]  DEFAULT ((0)) FOR [SpecialOffer]
END


END
GO
/****** Object:  Default [DF__Hishop_Pr__Visti__5535A963]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__Hishop_Pr__Visti__5535A963]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Hishop_Pr__Visti__5535A963]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_Products] ADD  CONSTRAINT [DF__Hishop_Pr__Visti__5535A963]  DEFAULT ((0)) FOR [VistiCounts]
END


END
GO
/****** Object:  Default [DF__Hishop_Pr__Displ__5629CD9C]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__Hishop_Pr__Displ__5629CD9C]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__Hishop_Pr__Displ__5629CD9C]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_Products] ADD  CONSTRAINT [DF__Hishop_Pr__Displ__5629CD9C]  DEFAULT ((0)) FOR [DisplaySequence]
END


END
GO
/****** Object:  Default [DF_Hishop_UserProfile_EnableDisplayInMemberList]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_UserProfile_EnableDisplayInMemberList]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_UserProfile_EnableDisplayInMemberList]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_UserProfile] ADD  CONSTRAINT [DF_Hishop_UserProfile_EnableDisplayInMemberList]  DEFAULT ((1)) FOR [EnableDisplayInMemberList]
END


END
GO
/****** Object:  Default [DF_Hishop_UserProfile_EnablePrivateMessages]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_UserProfile_EnablePrivateMessages]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_UserProfile_EnablePrivateMessages]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_UserProfile] ADD  CONSTRAINT [DF_Hishop_UserProfile_EnablePrivateMessages]  DEFAULT ((1)) FOR [EnablePrivateMessages]
END


END
GO
/****** Object:  Default [DF_Hishop_UserProfile_EnableOnlineStatus]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_UserProfile_EnableOnlineStatus]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_UserProfile_EnableOnlineStatus]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_UserProfile] ADD  CONSTRAINT [DF_Hishop_UserProfile_EnableOnlineStatus]  DEFAULT ((1)) FOR [EnableOnlineStatus]
END


END
GO
/****** Object:  Default [DF_Hishop_UserProfile_EnableEmail]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_UserProfile_EnableEmail]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_UserProfile_EnableEmail]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_UserProfile] ADD  CONSTRAINT [DF_Hishop_UserProfile_EnableEmail]  DEFAULT ((1)) FOR [EnableEmail]
END


END
GO
/****** Object:  Default [DF_Hishop_UserProfile_EnableHtmlEmail]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_UserProfile_EnableHtmlEmail]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_UserProfile_EnableHtmlEmail]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_UserProfile] ADD  CONSTRAINT [DF_Hishop_UserProfile_EnableHtmlEmail]  DEFAULT ((1)) FOR [EnableHtmlEmail]
END


END
GO
/****** Object:  Default [DF_Hishop_UserProfile_IsIgnored]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_UserProfile_IsIgnored]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_UserProfile_IsIgnored]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_UserProfile] ADD  CONSTRAINT [DF_Hishop_UserProfile_IsIgnored]  DEFAULT ((0)) FOR [IsIgnored]
END


END
GO
/****** Object:  Default [DF_Hishop_UserProfile_PublicToken]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_UserProfile_PublicToken]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_UserProfile_PublicToken]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_UserProfile] ADD  CONSTRAINT [DF_Hishop_UserProfile_PublicToken]  DEFAULT (newid()) FOR [PublicToken]
END


END
GO
/****** Object:  Default [DF_Hishop_UserProfile_Expenditure]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_UserProfile_Expenditure]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_UserProfile_Expenditure]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_UserProfile] ADD  CONSTRAINT [DF_Hishop_UserProfile_Expenditure]  DEFAULT ((0)) FOR [Expenditure]
END


END
GO
/****** Object:  Default [DF_Hishop_UserProfile_EnableTradePassword]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_UserProfile_EnableTradePassword]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_UserProfile_EnableTradePassword]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_UserProfile] ADD  CONSTRAINT [DF_Hishop_UserProfile_EnableTradePassword]  DEFAULT ((0)) FOR [EnableTradePassword]
END


END
GO
/****** Object:  Default [DF_Hishop_UserProfile_TradePasswordFormat]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_UserProfile_TradePasswordFormat]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_UserProfile_TradePasswordFormat]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_UserProfile] ADD  CONSTRAINT [DF_Hishop_UserProfile_TradePasswordFormat]  DEFAULT ((0)) FOR [TradePasswordFormat]
END


END
GO
/****** Object:  Default [DF_Hishop_UserProfile_Points]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_UserProfile_Points]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_UserProfile_Points]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_UserProfile] ADD  CONSTRAINT [DF_Hishop_UserProfile_Points]  DEFAULT ((0)) FOR [Points]
END


END
GO
/****** Object:  Default [DF_Hishop_Users_ForceLogin]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_Users_ForceLogin]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_Users_ForceLogin]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_Users] ADD  CONSTRAINT [DF_Hishop_Users_ForceLogin]  DEFAULT ((0)) FOR [ForceLogin]
END


END
GO
/****** Object:  Default [DF_Hishop_Users_UserAccountStatus]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_Users_UserAccountStatus]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_Users_UserAccountStatus]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_Users] ADD  CONSTRAINT [DF_Hishop_Users_UserAccountStatus]  DEFAULT ((1)) FOR [UserAccountStatus]
END


END
GO
/****** Object:  Default [DF_Hishop_Users_LastActivity]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_Users_LastActivity]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_Users_LastActivity]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_Users] ADD  CONSTRAINT [DF_Hishop_Users_LastActivity]  DEFAULT (getdate()) FOR [LastActivity]
END


END
GO
/****** Object:  Default [DF_Hishop_Users_LastAction]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_Users_LastAction]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_Users_LastAction]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_Users] ADD  CONSTRAINT [DF_Hishop_Users_LastAction]  DEFAULT ('') FOR [LastAction]
END


END
GO
/****** Object:  Default [DF_Hishop_Users_Deleted]    Script Date: 04/20/2009 16:21:45 ******/
IF Not EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF_Hishop_Users_Deleted]') AND type = 'D')
BEGIN
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF_Hishop_Users_Deleted]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Hishop_Users] ADD  CONSTRAINT [DF_Hishop_Users_Deleted]  DEFAULT ((0)) FOR [Deleted]
END


END
GO
/****** Object:  ForeignKey [FK__aspnet_Me__Appli__0EA330E9]    Script Date: 04/20/2009 16:21:45 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Me__Appli__0EA330E9]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_Membership]  WITH CHECK ADD  CONSTRAINT [FK__aspnet_Me__Appli__0EA330E9] FOREIGN KEY([ApplicationId])
REFERENCES [dbo].[aspnet_Applications] ([ApplicationId])
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Me__Appli__0EA330E9]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_Membership] CHECK CONSTRAINT [FK__aspnet_Me__Appli__0EA330E9]
GO
/****** Object:  ForeignKey [FK__aspnet_Me__UserI__0F975522]    Script Date: 04/20/2009 16:21:45 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Me__UserI__0F975522]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_Membership]  WITH CHECK ADD  CONSTRAINT [FK__aspnet_Me__UserI__0F975522] FOREIGN KEY([UserId])
REFERENCES [dbo].[aspnet_Users] ([UserId])
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Me__UserI__0F975522]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_Membership] CHECK CONSTRAINT [FK__aspnet_Me__UserI__0F975522]
GO
/****** Object:  ForeignKey [FK__aspnet_Pr__UserI__239E4DCF]    Script Date: 04/20/2009 16:21:45 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Pr__UserI__239E4DCF]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_Profile]  WITH CHECK ADD  CONSTRAINT [FK__aspnet_Pr__UserI__239E4DCF] FOREIGN KEY([UserId])
REFERENCES [dbo].[aspnet_Users] ([UserId])
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Pr__UserI__239E4DCF]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_Profile] CHECK CONSTRAINT [FK__aspnet_Pr__UserI__239E4DCF]
GO
/****** Object:  ForeignKey [FK__aspnet_Ro__Appli__2D27B809]    Script Date: 04/20/2009 16:21:45 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Ro__Appli__2D27B809]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_Roles]  WITH CHECK ADD  CONSTRAINT [FK__aspnet_Ro__Appli__2D27B809] FOREIGN KEY([ApplicationId])
REFERENCES [dbo].[aspnet_Applications] ([ApplicationId])
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Ro__Appli__2D27B809]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_Roles] CHECK CONSTRAINT [FK__aspnet_Ro__Appli__2D27B809]
GO
/****** Object:  ForeignKey [FK__aspnet_Us__Appli__7E6CC920]    Script Date: 04/20/2009 16:21:45 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Us__Appli__7E6CC920]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_Users]  WITH CHECK ADD  CONSTRAINT [FK__aspnet_Us__Appli__7E6CC920] FOREIGN KEY([ApplicationId])
REFERENCES [dbo].[aspnet_Applications] ([ApplicationId])
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Us__Appli__7E6CC920]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_Users] CHECK CONSTRAINT [FK__aspnet_Us__Appli__7E6CC920]
GO
/****** Object:  ForeignKey [FK__aspnet_Us__RoleI__31EC6D26]    Script Date: 04/20/2009 16:21:45 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Us__RoleI__31EC6D26]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_UsersInRoles]  WITH CHECK ADD  CONSTRAINT [FK__aspnet_Us__RoleI__31EC6D26] FOREIGN KEY([RoleId])
REFERENCES [dbo].[aspnet_Roles] ([RoleId])
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Us__RoleI__31EC6D26]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_UsersInRoles] CHECK CONSTRAINT [FK__aspnet_Us__RoleI__31EC6D26]
GO
/****** Object:  ForeignKey [FK__aspnet_Us__UserI__30F848ED]    Script Date: 04/20/2009 16:21:45 ******/
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Us__UserI__30F848ED]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_UsersInRoles]  WITH CHECK ADD  CONSTRAINT [FK__aspnet_Us__UserI__30F848ED] FOREIGN KEY([UserId])
REFERENCES [dbo].[aspnet_Users] ([UserId])
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FK__aspnet_Us__UserI__30F848ED]') AND type = 'F')
ALTER TABLE [dbo].[aspnet_UsersInRoles] CHECK CONSTRAINT [FK__aspnet_Us__UserI__30F848ED]
GO
GRANT EXECUTE ON [dbo].[aspnet_CheckSchemaVersion] TO [aspnet_Membership_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_CheckSchemaVersion] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_CheckSchemaVersion] TO [aspnet_Personalization_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_CheckSchemaVersion] TO [aspnet_Personalization_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_CheckSchemaVersion] TO [aspnet_Profile_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_CheckSchemaVersion] TO [aspnet_Profile_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_CheckSchemaVersion] TO [aspnet_Roles_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_CheckSchemaVersion] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_CheckSchemaVersion] TO [aspnet_WebEvent_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_ChangePasswordQuestionAndAnswer] TO [aspnet_Membership_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_CreateUser] TO [aspnet_Membership_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_FindUsersByEmail] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_FindUsersByName] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_GetAllUsers] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_GetNumberOfUsersOnline] TO [aspnet_Membership_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_GetNumberOfUsersOnline] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_GetPassword] TO [aspnet_Membership_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_GetPasswordWithFormat] TO [aspnet_Membership_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_GetUserByEmail] TO [aspnet_Membership_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_GetUserByEmail] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_GetUserByName] TO [aspnet_Membership_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_GetUserByName] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_GetUserByUserId] TO [aspnet_Membership_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_GetUserByUserId] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_ResetPassword] TO [aspnet_Membership_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_SetPassword] TO [aspnet_Membership_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_UnlockUser] TO [aspnet_Membership_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_UpdateUser] TO [aspnet_Membership_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Membership_UpdateUserInfo] TO [aspnet_Membership_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Profile_DeleteInactiveProfiles] TO [aspnet_Profile_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Profile_DeleteProfiles] TO [aspnet_Profile_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Profile_GetNumberOfInactiveProfiles] TO [aspnet_Profile_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Profile_GetProfiles] TO [aspnet_Profile_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Profile_GetProperties] TO [aspnet_Profile_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Profile_SetProperties] TO [aspnet_Profile_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_RegisterSchemaVersion] TO [aspnet_Membership_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_RegisterSchemaVersion] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_RegisterSchemaVersion] TO [aspnet_Personalization_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_RegisterSchemaVersion] TO [aspnet_Personalization_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_RegisterSchemaVersion] TO [aspnet_Profile_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_RegisterSchemaVersion] TO [aspnet_Profile_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_RegisterSchemaVersion] TO [aspnet_Roles_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_RegisterSchemaVersion] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_RegisterSchemaVersion] TO [aspnet_WebEvent_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Roles_CreateRole] TO [aspnet_Roles_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Roles_DeleteRole] TO [aspnet_Roles_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Roles_GetAllRoles] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Roles_RoleExists] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UnRegisterSchemaVersion] TO [aspnet_Membership_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UnRegisterSchemaVersion] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UnRegisterSchemaVersion] TO [aspnet_Personalization_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UnRegisterSchemaVersion] TO [aspnet_Personalization_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UnRegisterSchemaVersion] TO [aspnet_Profile_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UnRegisterSchemaVersion] TO [aspnet_Profile_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UnRegisterSchemaVersion] TO [aspnet_Roles_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UnRegisterSchemaVersion] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UnRegisterSchemaVersion] TO [aspnet_WebEvent_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_Users_DeleteUser] TO [aspnet_Membership_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UsersInRoles_AddUsersToRoles] TO [aspnet_Roles_FullAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UsersInRoles_FindUsersInRole] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UsersInRoles_GetRolesForUser] TO [aspnet_Roles_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UsersInRoles_GetRolesForUser] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UsersInRoles_GetUsersInRoles] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UsersInRoles_IsUserInRole] TO [aspnet_Roles_BasicAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UsersInRoles_IsUserInRole] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT EXECUTE ON [dbo].[aspnet_UsersInRoles_RemoveUsersFromRoles] TO [aspnet_Roles_FullAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_Applications] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_Applications] TO [aspnet_Personalization_ReportingAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_Applications] TO [aspnet_Profile_ReportingAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_Applications] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_MembershipUsers] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_Profiles] TO [aspnet_Profile_ReportingAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_Roles] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_Users] TO [aspnet_Membership_ReportingAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_Users] TO [aspnet_Personalization_ReportingAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_Users] TO [aspnet_Profile_ReportingAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_Users] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
GRANT SELECT ON [dbo].[vw_aspnet_UsersInRoles] TO [aspnet_Roles_ReportingAccess] AS [dbo]
GO
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Membership_BasicAccess')
BEGIN
EXEC dbo.sp_addrolemember @rolename=N'aspnet_Membership_BasicAccess', @membername=N'aspnet_Membership_FullAccess'

END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Membership_ReportingAccess')
BEGIN
EXEC dbo.sp_addrolemember @rolename=N'aspnet_Membership_ReportingAccess', @membername=N'aspnet_Membership_FullAccess'

END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Profile_BasicAccess')
BEGIN
EXEC dbo.sp_addrolemember @rolename=N'aspnet_Profile_BasicAccess', @membername=N'aspnet_Profile_FullAccess'

END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Profile_ReportingAccess')
BEGIN
EXEC dbo.sp_addrolemember @rolename=N'aspnet_Profile_ReportingAccess', @membername=N'aspnet_Profile_FullAccess'

END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Roles_BasicAccess')
BEGIN
EXEC dbo.sp_addrolemember @rolename=N'aspnet_Roles_BasicAccess', @membername=N'aspnet_Roles_FullAccess'

END
GO
IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'aspnet_Roles_ReportingAccess')
BEGIN
EXEC dbo.sp_addrolemember @rolename=N'aspnet_Roles_ReportingAccess', @membername=N'aspnet_Roles_FullAccess'

END
GO
