USE [master]
GO
/****** Object:  Database [World00_Character]    Script Date: 12/20/2015 6:11:00 PM ******/
CREATE DATABASE [World00_Character]
 CONTAINMENT = NONE
 ON  PRIMARY 
( NAME = N'World00_Character', FILENAME = N'D:\SQL SERVER DATA\SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\World00_Character.mdf' , SIZE = 7168KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'World00_Character_log', FILENAME = N'D:\SQL SERVER DATA\SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\World00_Character_1.ldf' , SIZE = 22144KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
ALTER DATABASE [World00_Character] SET COMPATIBILITY_LEVEL = 110
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [World00_Character].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [World00_Character] SET ANSI_NULL_DEFAULT OFF 
GO
ALTER DATABASE [World00_Character] SET ANSI_NULLS OFF 
GO
ALTER DATABASE [World00_Character] SET ANSI_PADDING OFF 
GO
ALTER DATABASE [World00_Character] SET ANSI_WARNINGS OFF 
GO
ALTER DATABASE [World00_Character] SET ARITHABORT OFF 
GO
ALTER DATABASE [World00_Character] SET AUTO_CLOSE OFF 
GO
ALTER DATABASE [World00_Character] SET AUTO_SHRINK OFF 
GO
ALTER DATABASE [World00_Character] SET AUTO_UPDATE_STATISTICS ON 
GO
ALTER DATABASE [World00_Character] SET CURSOR_CLOSE_ON_COMMIT OFF 
GO
ALTER DATABASE [World00_Character] SET CURSOR_DEFAULT  GLOBAL 
GO
ALTER DATABASE [World00_Character] SET CONCAT_NULL_YIELDS_NULL OFF 
GO
ALTER DATABASE [World00_Character] SET NUMERIC_ROUNDABORT OFF 
GO
ALTER DATABASE [World00_Character] SET QUOTED_IDENTIFIER OFF 
GO
ALTER DATABASE [World00_Character] SET RECURSIVE_TRIGGERS OFF 
GO
ALTER DATABASE [World00_Character] SET  DISABLE_BROKER 
GO
ALTER DATABASE [World00_Character] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
GO
ALTER DATABASE [World00_Character] SET DATE_CORRELATION_OPTIMIZATION OFF 
GO
ALTER DATABASE [World00_Character] SET TRUSTWORTHY OFF 
GO
ALTER DATABASE [World00_Character] SET ALLOW_SNAPSHOT_ISOLATION OFF 
GO
ALTER DATABASE [World00_Character] SET PARAMETERIZATION SIMPLE 
GO
ALTER DATABASE [World00_Character] SET READ_COMMITTED_SNAPSHOT OFF 
GO
ALTER DATABASE [World00_Character] SET HONOR_BROKER_PRIORITY OFF 
GO
ALTER DATABASE [World00_Character] SET RECOVERY SIMPLE 
GO
ALTER DATABASE [World00_Character] SET  MULTI_USER 
GO
ALTER DATABASE [World00_Character] SET PAGE_VERIFY CHECKSUM  
GO
ALTER DATABASE [World00_Character] SET DB_CHAINING OFF 
GO
ALTER DATABASE [World00_Character] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) 
GO
ALTER DATABASE [World00_Character] SET TARGET_RECOVERY_TIME = 0 SECONDS 
GO
ALTER DATABASE [World00_Character] SET DELAYED_DURABILITY = DISABLED 
GO
USE [World00_Character]
GO
/****** Object:  User [Stormy-PC\Administrator]    Script Date: 12/20/2015 6:11:00 PM ******/
CREATE USER [Stormy-PC\Administrator] FOR LOGIN [Stormy-PC\Administrator] WITH DEFAULT_SCHEMA=[dbo]
GO
/****** Object:  User [NT AUTHORITY\SYSTEM]    Script Date: 12/20/2015 6:11:00 PM ******/
CREATE USER [NT AUTHORITY\SYSTEM] FOR LOGIN [NT AUTHORITY\SYSTEM] WITH DEFAULT_SCHEMA=[dbo]
GO
ALTER ROLE [db_owner] ADD MEMBER [Stormy-PC\Administrator]
GO
ALTER ROLE [db_accessadmin] ADD MEMBER [Stormy-PC\Administrator]
GO
ALTER ROLE [db_securityadmin] ADD MEMBER [Stormy-PC\Administrator]
GO
ALTER ROLE [db_ddladmin] ADD MEMBER [Stormy-PC\Administrator]
GO
ALTER ROLE [db_backupoperator] ADD MEMBER [Stormy-PC\Administrator]
GO
ALTER ROLE [db_datareader] ADD MEMBER [Stormy-PC\Administrator]
GO
ALTER ROLE [db_datawriter] ADD MEMBER [Stormy-PC\Administrator]
GO
ALTER ROLE [db_denydatareader] ADD MEMBER [Stormy-PC\Administrator]
GO
ALTER ROLE [db_denydatawriter] ADD MEMBER [Stormy-PC\Administrator]
GO
ALTER ROLE [db_owner] ADD MEMBER [NT AUTHORITY\SYSTEM]
GO
ALTER ROLE [db_accessadmin] ADD MEMBER [NT AUTHORITY\SYSTEM]
GO
ALTER ROLE [db_securityadmin] ADD MEMBER [NT AUTHORITY\SYSTEM]
GO
ALTER ROLE [db_ddladmin] ADD MEMBER [NT AUTHORITY\SYSTEM]
GO
ALTER ROLE [db_backupoperator] ADD MEMBER [NT AUTHORITY\SYSTEM]
GO
ALTER ROLE [db_datareader] ADD MEMBER [NT AUTHORITY\SYSTEM]
GO
ALTER ROLE [db_datawriter] ADD MEMBER [NT AUTHORITY\SYSTEM]
GO
ALTER ROLE [db_denydatareader] ADD MEMBER [NT AUTHORITY\SYSTEM]
GO
ALTER ROLE [db_denydatawriter] ADD MEMBER [NT AUTHORITY\SYSTEM]
GO
/****** Object:  UserDefinedFunction [dbo].[fn_Auction_getCategory]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 테이블 : fn_Auction_getCategory
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2011년 01월 11일
' Description : 
'	카테고리 테이블을 검색하여 자신의 하위 카테고리 테이블을 모두 포함한 결과를
'	리턴하는 함수.

'	처음 부모 카테고리를 검색하여 존재한다면 하위 카테고리를 반복적으로 찾아
'	테이블 변수에 depth(깊이)만큼 계속 삽입하여 카테고리 리스트 테이블을 생성하는 원리.
'	depth가 존재해야 하는 이유는 무한 반복적으로 찾는 것을 방지하는 것이 목적임.
'-------------------------------------------------------------------------------------*/
CREATE FUNCTION [dbo].[fn_Auction_getCategory] (@categoryNo int) 
	RETURNS @_category TABLE (
		categoryNo   int
	,	parentsNo    int)
AS
BEGIN
	DECLARE @depth int
	SET @depth = 1

	DECLARE @retCategory TABLE (
		categoryNo   int
	,	parentsNo    int
	,	depth        tinyint)		

	INSERT INTO @retCategory
	SELECT nCategoryNo, nParentsNo, @depth
	  FROM tAuctionCategory
	 WHERE nCategoryNo = @categoryNo
	WHILE @@rowcount > 0 BEGIN
		SET @depth = @depth + 1

		INSERT @retCategory
		SELECT T1.nCategoryNo, T1.nParentsNo, @depth
		  FROM tAuctionCategory AS T1, @retCategory AS T2
		 WHERE T1.nParentsNo = T2.categoryNo AND T2.depth = @depth - 1
	END

	INSERT @_category
		SELECT categoryNo, parentsNo
		  FROM @retCategory
		 ORDER BY categoryNo

	RETURN
END


GO
/****** Object:  Table [dbo].[LoggedInChars]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LoggedInChars](
	[nCharNo] [int] NOT NULL,
	[nUserNo] [int] NULL,
	[nAdminLevel] [tinyint] NULL,
	[sID] [nvarchar](40) NULL,
	[sLoginZone] [nvarchar](16) NULL,
	[nLoginCount] [int] NULL,
	[nPlayMin] [int] NULL,
	[nClass] [tinyint] NULL,
	[nLevel] [smallint] NULL,
	[nExp] [bigint] NULL,
	[nFame] [int] NULL,
	[nCoin] [bigint] NULL,
	[nMoney] [bigint] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tAttendance]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tAttendance](
	[nCharNo] [int] NOT NULL,
	[dAttendanceDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[dAttendanceDate] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tAttendanceReward]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tAttendanceReward](
	[nCharNo] [int] NOT NULL,
	[dEventDate] [datetime] NOT NULL,
	[dRewardDate] [datetime] NOT NULL,
	[nRewardID] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[dEventDate] ASC,
	[nRewardID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tAuction]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tAuction](
	[nAuctionNo] [int] IDENTITY(1,1) NOT NULL,
	[sys_create_date] [datetime] NOT NULL,
	[sys_update_date] [datetime] NULL,
	[nCategoryNo] [tinyint] NOT NULL,
	[nSellerNo] [int] NOT NULL,
	[nRegistration] [bigint] NOT NULL,
	[dSellStartDate] [datetime] NOT NULL,
	[dSellEndDate] [datetime] NOT NULL,
	[nSellPrice] [bigint] NOT NULL,
	[nItemKey] [bigint] NOT NULL,
	[nItemID] [int] NOT NULL,
	[nItemLevel] [smallint] NOT NULL,
	[nItemGrade] [tinyint] NOT NULL,
	[sItemName] [nvarchar](64) NOT NULL,
	[nBidderNo] [int] NULL,
	[dBidDate] [datetime] NULL,
	[nSellCharge] [bigint] NULL,
	[nStatus] [tinyint] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nAuctionNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tAuctionCategory]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tAuctionCategory](
	[nCategoryNo] [tinyint] NOT NULL,
	[sys_create_date] [datetime] NOT NULL DEFAULT (getdate()),
	[sys_update_date] [datetime] NULL,
	[sCategoryName] [nvarchar](30) NOT NULL,
	[bIsActive] [bit] NOT NULL DEFAULT ((0)),
	[nParentsNo] [tinyint] NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nCategoryNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tAuctionInventory]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tAuctionInventory](
	[nCharNo] [int] NOT NULL,
	[nAuctionNo] [int] NOT NULL,
	[sys_create_date] [datetime] NOT NULL,
	[sys_update_date] [datetime] NULL,
	[nInventoryType] [tinyint] NOT NULL,
	[dStartDate] [datetime] NOT NULL,
	[dEndDate] [datetime] NOT NULL,
	[nMoney] [bigint] NULL,
	[nItemKey] [bigint] NULL,
	[bIsDelete] [bit] NOT NULL,
	[dDeleteDate] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nAuctionNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacter]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacter](
	[nCharNo] [int] IDENTITY(1,1) NOT NULL,
	[sID] [nvarchar](40) NOT NULL,
	[nUserNo] [int] NOT NULL,
	[nAdminLevel] [tinyint] NOT NULL DEFAULT ((0)),
	[nPS] [int] NOT NULL DEFAULT ((0)),
	[nGS] [int] NOT NULL DEFAULT ((0)),
	[dCreateDate] [datetime] NOT NULL DEFAULT (getdate()),
	[bDeleted] [tinyint] NOT NULL DEFAULT ((0)),
	[nLoginZoneX] [int] NOT NULL DEFAULT ((0)),
	[nLoginZoneY] [int] NOT NULL DEFAULT ((0)),
	[nLoginZoneD] [tinyint] NOT NULL DEFAULT ((0)),
	[nPKYellowTime] [tinyint] NOT NULL DEFAULT ((0)),
	[dDeletedDate] [datetime] NOT NULL DEFAULT (getdate()),
	[nAP] [smallint] NOT NULL DEFAULT ((0)),
	[sLoginZone] [nvarchar](16) NOT NULL DEFAULT (''),
	[nPKCount] [int] NOT NULL DEFAULT ((0)),
	[nLevel] [smallint] NOT NULL DEFAULT ((1)),
	[nExp] [bigint] NOT NULL DEFAULT ((0)),
	[nSlotNo] [tinyint] NOT NULL DEFAULT ((0)),
	[nHP] [smallint] NOT NULL DEFAULT ((0)),
	[nSP] [smallint] NOT NULL DEFAULT ((0)),
	[nHPS] [smallint] NOT NULL DEFAULT ((0)),
	[nSPS] [smallint] NOT NULL DEFAULT ((0)),
	[dLastLoginDate] [datetime] NOT NULL DEFAULT (getdate()),
	[nLoginCount] [int] NOT NULL DEFAULT ((0)),
	[nCreateWorld] [tinyint] NOT NULL DEFAULT ((0)),
	[nFame] [int] NOT NULL DEFAULT ((0)),
	[nPrisonMin] [smallint] NOT NULL DEFAULT ((0)),
	[nPlayMin] [int] NOT NULL DEFAULT ((0)),
	[nFlags] [int] NOT NULL DEFAULT ((0)),
	[nMoney] [bigint] NOT NULL DEFAULT ((0)),
	[nStrength] [tinyint] NOT NULL DEFAULT ((0)),
	[nConstitute] [tinyint] NOT NULL DEFAULT ((0)),
	[nDexterity] [tinyint] NOT NULL DEFAULT ((0)),
	[nIntelligence] [tinyint] NOT NULL DEFAULT ((0)),
	[nMentalPower] [tinyint] NOT NULL DEFAULT ((0)),
	[nRedistributePoint] [tinyint] NOT NULL DEFAULT ((0)),
	[nKQHandle] [int] NOT NULL DEFAULT ((-1)),
	[sKQMap] [nvarchar](16) NOT NULL DEFAULT (''),
	[nKQX] [int] NOT NULL DEFAULT ((0)),
	[nKQY] [int] NOT NULL DEFAULT ((0)),
	[nKQD] [tinyint] NOT NULL DEFAULT ((0)),
	[dKQDate] [datetime] NOT NULL DEFAULT (getdate()),
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterChangeID]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterChangeID](
	[nRowNo] [int] IDENTITY(1,1) NOT NULL,
	[sys_create_date] [datetime] NOT NULL,
	[sys_update_date] [datetime] NULL,
	[nUserNo] [int] NOT NULL,
	[nCharNo] [int] NOT NULL,
	[bFlag] [bit] NOT NULL,
	[bInit] [bit] NOT NULL,
	[sOldID] [nvarchar](50) NULL,
	[sNewID] [nvarchar](50) NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nRowNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterChargedBuffer]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterChargedBuffer](
	[nNo] [int] IDENTITY(1,1) NOT NULL,
	[nCharNo] [int] NOT NULL,
	[nKey] [int] NOT NULL,
	[nID] [smallint] NOT NULL,
	[dUseDate] [datetime] NOT NULL,
	[dEndDate] [datetime] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterDisposition]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterDisposition](
	[nCharNo] [int] NOT NULL,
	[nDisposition] [tinyint] NOT NULL,
	[nKillCount] [int] NOT NULL,
	[nKillPoint] [int] NOT NULL,
	[nChaosPoint] [int] NOT NULL,
	[nNeutralTime] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterGameOption]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterGameOption](
	[nCharNo] [int] NOT NULL,
	[sys_create_date] [datetime] NOT NULL DEFAULT (getdate()),
	[nOptionNo] [smallint] NOT NULL,
	[nValue] [tinyint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nOptionNo] ASC,
	[nValue] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterKeyMap]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterKeyMap](
	[nCharNo] [int] NOT NULL,
	[nFunctionNo] [smallint] NOT NULL,
	[sys_create_date] [datetime] NOT NULL DEFAULT (getdate()),
	[sys_update_date] [datetime] NULL,
	[nExtendedKey] [tinyint] NULL,
	[nASCIICode] [tinyint] NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nFunctionNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterLoading]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterLoading](
	[nCharNo] [int] NOT NULL,
	[nSeqNo] [int] NOT NULL,
	[dWorldTime] [datetime] NOT NULL,
	[dDBTime] [datetime] NOT NULL,
	[sLoadingMapName] [nvarchar](16) NOT NULL,
	[nFailType] [smallint] NOT NULL,
	[nLoadingFailCnt] [smallint] NOT NULL,
	[sFromMapName] [nvarchar](16) NULL,
	[nFromZoneIP] [nvarchar](16) NULL,
	[nToZoneIP] [nvarchar](16) NULL,
	[nToZonePort] [smallint] NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nSeqNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterLoadingDetailInfo]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterLoadingDetailInfo](
	[nCharNo] [int] NOT NULL,
	[nSeqNo] [int] NOT NULL,
	[nErrorNo] [int] NOT NULL,
	[nErrorData] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nSeqNo] ASC,
	[nErrorNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterOptions]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tCharacterOptions](
	[nCharNo] [int] NOT NULL,
	[sShortCutData] [varbinary](1024) NULL,
	[sShortCutSize] [varbinary](24) NULL,
	[sVideo] [varbinary](60) NULL,
	[sSound] [varbinary](1) NULL,
	[sGame] [varbinary](64) NULL,
	[sWindowsPos] [varbinary](392) NULL,
	[sKeyMapping] [varbinary](308) NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[tCharacterShape]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterShape](
	[nCharNo] [int] NOT NULL,
	[nClass] [tinyint] NOT NULL DEFAULT ((0)),
	[nRace] [tinyint] NOT NULL DEFAULT ((0)),
	[nGender] [tinyint] NOT NULL DEFAULT ((0)),
	[nHairType] [tinyint] NOT NULL DEFAULT ((0)),
	[nHairColor] [tinyint] NOT NULL DEFAULT ((0)),
	[nFaceShape] [tinyint] NOT NULL DEFAULT ((0)),
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterShortCut]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterShortCut](
	[nCharNo] [int] NOT NULL,
	[nSlotNo] [tinyint] NOT NULL,
	[sys_create_date] [datetime] NOT NULL DEFAULT (getdate()),
	[sys_update_date] [datetime] NOT NULL DEFAULT (getdate()),
	[nCodeType] [smallint] NOT NULL,
	[nCodeNo] [smallint] NOT NULL,
	[nValue] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nSlotNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterSingleOption]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterSingleOption](
	[nCharNo] [int] NOT NULL,
	[sys_create_date] [datetime] NOT NULL DEFAULT (getdate()),
	[sys_update_date] [datetime] NULL,
	[bMysteryBolt] [bit] NOT NULL DEFAULT ((1)),
	[bAutoPick] [bit] NOT NULL DEFAULT ((0)),
	[dRestExpLastExecuteTime] [datetime] NOT NULL DEFAULT (getdate()),
	[nChatBan] [int] NOT NULL DEFAULT ((0)),
	[bAuction] [bit] NOT NULL DEFAULT ((0)),
	[dNoMannerEndDate] [datetime] NOT NULL DEFAULT (getdate()),
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterState]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterState](
	[nCharNo] [int] NOT NULL,
	[nStateNo] [smallint] NOT NULL,
	[nStateLevel] [smallint] NOT NULL,
	[nStateTime] [int] NOT NULL,
	[nStateCount] [smallint] NOT NULL DEFAULT ((0)),
	[nStatePowerDemage] [tinyint] NOT NULL DEFAULT ((0)),
	[nStatePowerSP] [tinyint] NOT NULL DEFAULT ((0)),
	[nStatePowerKeepTime] [tinyint] NOT NULL DEFAULT ((0)),
	[nStatePowerCoolTime] [tinyint] NOT NULL DEFAULT ((0)),
	[nSetItemIndexA] [smallint] NOT NULL DEFAULT ((0)),
	[nSetItemValueA] [smallint] NOT NULL DEFAULT ((0)),
	[nSetItemIndexB] [smallint] NOT NULL DEFAULT ((0)),
	[nSetItemValueB] [smallint] NOT NULL DEFAULT ((0)),
	[nSetItemIndexC] [smallint] NOT NULL DEFAULT ((0)),
	[nSetItemValueC] [smallint] NOT NULL DEFAULT ((0)),
	[nSetItemIndexD] [smallint] NOT NULL DEFAULT ((0)),
	[nSetItemValueD] [smallint] NOT NULL DEFAULT ((0)),
	[nRestTime] [int] NOT NULL DEFAULT ((0)),
	[nCasterLevel] [smallint] NULL DEFAULT ((0)),
	[nCasterAttackPower] [int] NULL DEFAULT ((0)),
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nStateNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCharacterTitle]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCharacterTitle](
	[nNo] [bigint] IDENTITY(1,1) NOT NULL,
	[dDate] [datetime] NOT NULL DEFAULT (getdate()),
	[nCharNo] [int] NOT NULL,
	[nType] [tinyint] NOT NULL,
	[nElementNo] [tinyint] NOT NULL,
	[nElementValue] [bigint] NOT NULL DEFAULT ((0)),
PRIMARY KEY NONCLUSTERED 
(
	[nNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tChatBlock]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tChatBlock](
	[nUserNo] [int] NOT NULL,
	[nCharNo] [int] NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nUserNo] ASC,
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCollectionCard]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCollectionCard](
	[nCharNo] [int] NOT NULL,
	[nCardID] [int] NOT NULL,
	[nSerialNo] [bigint] NOT NULL,
	[nStarNumber] [tinyint] NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nCardID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCollectionFavorites]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCollectionFavorites](
	[nCharNo] [int] NOT NULL,
	[nSlotNo] [tinyint] NOT NULL,
	[nCardID] [int] NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nSlotNo] ASC,
	[nCardID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCollectionReward]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCollectionReward](
	[nCharNo] [int] NOT NULL,
	[nReward] [int] NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nReward] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tCollectionSerialCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tCollectionSerialCount](
	[nCardID] [int] NOT NULL,
	[sys_create_date] [datetime] NOT NULL,
	[sys_update_date] [datetime] NULL,
	[nCount] [bigint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCardID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tDice]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tDice](
	[nGameNo] [int] IDENTITY(1,1) NOT NULL,
	[nCharNo] [int] NOT NULL,
	[nItemKey] [bigint] NOT NULL,
	[sDice] [nvarchar](3) NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nGameNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tDiceLog]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tDiceLog](
	[nGameNo] [int] NOT NULL,
	[nCustomCharNo] [int] NOT NULL,
	[nSlotNo] [tinyint] NOT NULL,
	[nBattingMoney] [bigint] NOT NULL,
	[nBattingRate] [int] NOT NULL,
	[bStatus] [bit] NOT NULL,
	[nTaxRate] [int] NOT NULL,
	[nDividend] [bigint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nGameNo] ASC,
	[nCustomCharNo] ASC,
	[nSlotNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tDicePayLog]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tDicePayLog](
	[nCharNo] [int] NOT NULL,
	[nItemKey] [bigint] NOT NULL,
	[nTotalDividend] [bigint] NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nItemKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tDiceResult]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tDiceResult](
	[nGameNo] [int] NOT NULL,
	[nCustomCharNo] [int] NOT NULL,
	[nBeforeMoney] [bigint] NOT NULL,
	[nTotalDividend] [bigint] NOT NULL,
	[nAfterMoney] [bigint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nGameNo] ASC,
	[nCustomCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tFriend]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tFriend](
	[nCharNo] [int] NOT NULL,
	[nFriendCharNo] [int] NOT NULL,
	[nFlags] [tinyint] NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nFriendCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGambleCoin]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGambleCoin](
	[nCharNo] [int] NOT NULL,
	[sys_update_date] [datetime] NULL,
	[nCoin] [bigint] NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGambleCoinExchangeLog]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGambleCoinExchangeLog](
	[nLogNo] [bigint] IDENTITY(1,1) NOT NULL,
	[nCharNo] [int] NOT NULL,
	[dDate] [datetime] NOT NULL,
	[nExchangedCoin] [bigint] NOT NULL,
	[nStatus] [tinyint] NOT NULL,
	[nBeforeCoin] [bigint] NOT NULL,
	[nAfterCoin] [bigint] NOT NULL,
	[nBeforeMoney] [bigint] NOT NULL,
	[nAfterMoney] [bigint] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nLogNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGambleDice]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGambleDice](
	[nGameNo] [int] IDENTITY(1,1) NOT NULL,
	[sDice] [nvarchar](3) NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nGameNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGambleDiceLog]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGambleDiceLog](
	[nGameNo] [int] NOT NULL,
	[nCharNo] [int] NOT NULL,
	[nSlotNo] [tinyint] NOT NULL,
	[nBattingMoney] [bigint] NOT NULL,
	[nBattingRate] [int] NOT NULL,
	[bStatus] [bit] NOT NULL,
	[nTaxRate] [int] NOT NULL,
	[nDividend] [bigint] NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nGameNo] ASC,
	[nCharNo] ASC,
	[nSlotNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGambleDiceResult]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGambleDiceResult](
	[nGameNo] [int] NOT NULL,
	[nCharNo] [int] NOT NULL,
	[nBeforeMoney] [bigint] NOT NULL,
	[nTotalDividend] [bigint] NOT NULL,
	[nAfterMoney] [bigint] NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nGameNo] ASC,
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGambleJackpot]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGambleJackpot](
	[sGameName] [nvarchar](20) NOT NULL,
	[nBattingUnit] [bigint] NOT NULL,
	[sys_create_date] [datetime] NOT NULL,
	[sys_update_date] [datetime] NOT NULL,
	[nJackpotCoin] [bigint] NOT NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGambleJackpotLog]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGambleJackpotLog](
	[nLogNo] [bigint] IDENTITY(1,1) NOT NULL,
	[sGameName] [nvarchar](20) NOT NULL,
	[nBattingUnit] [bigint] NOT NULL,
	[sID] [nvarchar](80) NOT NULL,
	[nJackpotCoin] [bigint] NOT NULL,
	[nGameNo] [bigint] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nLogNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGambleSlotMachineLog]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGambleSlotMachineLog](
	[nGameNo] [bigint] IDENTITY(1,1) NOT NULL,
	[nCharNo] [int] NOT NULL,
	[dDate] [datetime] NOT NULL,
	[nBattingUnit] [bigint] NOT NULL,
	[nBatting] [tinyint] NOT NULL,
	[sGameResult] [nvarchar](10) NOT NULL,
	[bIsWin] [bit] NOT NULL,
	[nPrizeCoin] [bigint] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nGameNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGameOptionInit]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGameOptionInit](
	[nOptionNo] [smallint] NOT NULL,
	[sys_create_date] [datetime] NOT NULL DEFAULT (getdate()),
	[sys_update_date] [datetime] NULL,
	[nDefaultValue] [tinyint] NULL,
	[bIsActive] [bit] NOT NULL,
	[sDescription] [nvarchar](100) NULL,
	[sDescriptionLocal] [nvarchar](100) NULL,
PRIMARY KEY CLUSTERED 
(
	[nOptionNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGuild]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGuild](
	[nNo] [int] IDENTITY(1,1) NOT NULL,
	[sName] [nvarchar](18) NOT NULL,
	[sPassword] [nvarchar](9) NOT NULL,
	[nMaxMembers] [smallint] NOT NULL DEFAULT ((15)),
	[nMoney] [bigint] NOT NULL DEFAULT ((0)),
	[nType] [tinyint] NOT NULL DEFAULT ((0)),
	[nGrade] [tinyint] NOT NULL DEFAULT ((1)),
	[nFame] [int] NOT NULL DEFAULT ((0)),
	[nStoneLevel] [smallint] NOT NULL DEFAULT ((1)),
	[nExp] [bigint] NOT NULL DEFAULT ((0)),
	[dCreateDate] [datetime] NOT NULL DEFAULT (getdate()),
	[dWarRequestDate] [datetime] NOT NULL DEFAULT (getdate()),
	[dWarStartDate] [datetime] NOT NULL DEFAULT (getdate()),
	[dWarEndDate] [datetime] NOT NULL DEFAULT (getdate()),
	[nWarEnemy] [int] NOT NULL DEFAULT ((0)),
	[nWarWinCount] [int] NOT NULL DEFAULT ((0)),
	[nWarLoseCount] [int] NOT NULL DEFAULT ((0)),
	[nWarDrawCount] [int] NOT NULL DEFAULT ((0)),
	[nDismissStatus] [tinyint] NOT NULL DEFAULT ((0)),
	[dDismissDate] [datetime] NOT NULL DEFAULT (getdate()),
	[sIntro] [nvarchar](128) NOT NULL DEFAULT (''),
	[dNotifyDate] [datetime] NOT NULL DEFAULT (getdate()),
	[sNotifyCharID] [nvarchar](17) NOT NULL DEFAULT (''),
	[sNotify] [nvarchar](512) NOT NULL DEFAULT (''),
PRIMARY KEY CLUSTERED 
(
	[nNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGuildAcademy]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGuildAcademy](
	[nNo] [int] NOT NULL,
	[nMasterCharNo] [int] NOT NULL,
	[nMaxMember] [smallint] NOT NULL,
	[nMoney] [bigint] NOT NULL DEFAULT ((0)),
	[nPoint] [int] NOT NULL DEFAULT ((0)),
	[dBuffEndTime] [datetime] NULL,
	[dNotifyDate] [datetime] NULL,
	[sNotify] [nvarchar](512) NULL,
	[sIntro] [nvarchar](128) NULL,
PRIMARY KEY CLUSTERED 
(
	[nNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGuildAcademyGraduate]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGuildAcademyGraduate](
	[nNo] [int] NOT NULL,
	[nCharNo] [int] NOT NULL,
	[sID] [nvarchar](40) NOT NULL,
	[nClass] [tinyint] NOT NULL,
	[nJoinLevel] [smallint] NOT NULL,
	[dJoinDate] [datetime] NOT NULL,
	[nGraduateLevel] [smallint] NOT NULL,
	[dGraduateDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nNo] ASC,
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGuildAcademyMember]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGuildAcademyMember](
	[nNo] [int] NOT NULL,
	[nCharNo] [int] NOT NULL,
	[nJoinLevel] [smallint] NOT NULL,
	[dJoinDate] [datetime] NOT NULL,
	[nGrade] [tinyint] NULL,
	[sIntro] [nvarchar](128) NULL,
	[nChatBanTime] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nNo] ASC,
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGuildAcademyRanking]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGuildAcademyRanking](
	[nRowNo] [int] IDENTITY(1,1) NOT NULL,
	[dDate] [datetime] NOT NULL,
	[nRanking] [int] NOT NULL,
	[nGuildNo] [int] NOT NULL,
	[sGuildName] [nvarchar](18) NOT NULL,
	[nMasterNo] [int] NOT NULL,
	[sMasterID] [nvarchar](40) NOT NULL,
	[nPoint] [int] NOT NULL,
	[nCount] [int] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nRowNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGuildAcademyReward]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGuildAcademyReward](
	[nNo] [int] NOT NULL,
	[nLevel] [smallint] NOT NULL,
	[nTypeID] [tinyint] NOT NULL,
	[nValue] [bigint] NULL,
	[nItemID] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[nNo] ASC,
	[nLevel] ASC,
	[nTypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGuildAcademyRewardType]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGuildAcademyRewardType](
	[nTypeID] [tinyint] NOT NULL,
	[sTypeName] [nvarchar](20) NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nTypeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGuildMember]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGuildMember](
	[nNo] [int] NOT NULL,
	[nCharNo] [int] NOT NULL,
	[dJoinDate] [datetime] NOT NULL DEFAULT (getdate()),
	[nGrade] [tinyint] NOT NULL DEFAULT ((0)),
	[nFlags] [int] NOT NULL DEFAULT ((0)),
	[nExpRatio] [smallint] NOT NULL DEFAULT ((0)),
	[sIntro] [nvarchar](64) NOT NULL DEFAULT (''),
PRIMARY KEY CLUSTERED 
(
	[nNo] ASC,
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGuildToken]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGuildToken](
	[nNo] [int] NOT NULL,
	[nToken] [bigint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nNo] ASC,
	[nToken] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGuildTournament]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGuildTournament](
	[nGTNo] [int] NOT NULL,
	[nType] [smallint] NOT NULL,
	[nData] [int] NOT NULL,
	[dDate] [datetime] NOT NULL DEFAULT (getdate()),
	[nGuildNo] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[nGTNo] ASC,
	[nType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tGuildTournamentRegist]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tGuildTournamentRegist](
	[nGTNo] [int] NOT NULL,
	[nNo] [int] NOT NULL,
	[nMoney] [bigint] NOT NULL,
	[dDate] [datetime] NOT NULL,
	[nSeed] [int] NOT NULL,
	[bChoice] [bit] NOT NULL,
	[bRefundNotice] [bit] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nGTNo] ASC,
	[nNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tHolyPromise]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tHolyPromise](
	[nCharNo] [int] NOT NULL,
	[nUpCharNo] [int] NOT NULL,
	[nFlags] [tinyint] NOT NULL,
	[dRegDate] [datetime] NOT NULL,
	[dRejoinableDate] [datetime] NOT NULL,
	[dMemberAcceptableDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nUpCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tHolyPromiseReward]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tHolyPromiseReward](
	[nCharNo] [int] NOT NULL,
	[nSeqNo] [int] NOT NULL,
	[nType] [tinyint] NOT NULL,
	[nMoney] [bigint] NOT NULL,
	[nRemainMoney] [bigint] NOT NULL,
	[nReceiptCharNo] [int] NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nSeqNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tInGameGuide]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tInGameGuide](
	[nCharNo] [int] NOT NULL,
	[nGuideNo] [int] NULL
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tInstanceDungeonCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tInstanceDungeonCount](
	[nCharNo] [int] NOT NULL,
	[sIDGroup] [nvarchar](50) NOT NULL,
	[nCount] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[sIDGroup] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tItem]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tItem](
	[nItemKey] [bigint] NOT NULL,
	[nStorageType] [tinyint] NOT NULL,
	[nOwner] [bigint] NOT NULL,
	[nStorage] [smallint] NOT NULL,
	[nItemID] [int] NOT NULL,
	[nFlags] [int] NOT NULL DEFAULT ((0)),
	[dDate] [datetime] NOT NULL DEFAULT (getdate()),
PRIMARY KEY NONCLUSTERED 
(
	[nItemKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tItemActionCoolTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tItemActionCoolTime](
	[nCharNo] [int] NOT NULL,
	[nActionGroup] [smallint] NOT NULL,
	[sys_create_date] [datetime] NOT NULL,
	[dEndTime] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nActionGroup] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tItemEnchant]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tItemEnchant](
	[nItemKey] [bigint] NOT NULL,
	[nSlot] [tinyint] NOT NULL,
	[nGemItemID] [int] NOT NULL,
	[nRestCount] [tinyint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nItemKey] ASC,
	[nSlot] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tItemMobList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tItemMobList](
	[nItemKey] [bigint] NOT NULL,
	[nMobID] [smallint] NOT NULL,
	[nGrade] [tinyint] NOT NULL,
	[nKillCount] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nItemKey] ASC,
	[nMobID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tItemOptions]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tItemOptions](
	[nItemKey] [bigint] NOT NULL,
	[nOptionType] [smallint] NOT NULL,
	[nOptionData] [bigint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nItemKey] ASC,
	[nOptionType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tItemStorageFindEmpty]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tItemStorageFindEmpty](
	[nStorage] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nStorage] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tItemTitle]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tItemTitle](
	[nItemKey] [bigint] NOT NULL,
	[nTitleType] [smallint] NOT NULL,
	[sTitle] [nvarchar](24) NOT NULL,
	[nTitleCharNo] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nItemKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tKeyMapInit]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tKeyMapInit](
	[nFunctionNo] [smallint] NOT NULL,
	[sys_create_date] [datetime] NOT NULL DEFAULT (getdate()),
	[sys_update_date] [datetime] NULL,
	[nExtendedKey] [tinyint] NULL,
	[nASCIICode] [tinyint] NOT NULL,
	[sDescription] [nvarchar](1000) NULL,
PRIMARY KEY CLUSTERED 
(
	[nFunctionNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tLog_GuildMasterChange]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tLog_GuildMasterChange](
	[nRowNo] [bigint] IDENTITY(1,1) NOT NULL,
	[nGuildNo] [int] NOT NULL,
	[dDate] [datetime] NOT NULL,
	[nOldGuildMaster] [int] NOT NULL,
	[nNewGuildMaster] [int] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nRowNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tMarriage]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tMarriage](
	[nCharNo] [int] NOT NULL,
	[nPartnerCharNo] [int] NOT NULL,
	[nStatus] [tinyint] NOT NULL DEFAULT ((0)),
	[nSubStatus] [tinyint] NOT NULL DEFAULT ((0)),
	[dWhen] [datetime] NOT NULL,
	[dSubWhen] [datetime] NOT NULL,
	[nMarriageCount] [tinyint] NOT NULL DEFAULT ((0)),
	[nDivorceCancel] [tinyint] NOT NULL DEFAULT ((0)),
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nPartnerCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tMinihouse]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tMinihouse](
	[nCharNo] [int] NOT NULL,
	[nVisitor] [int] NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tMinihouseGate]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tMinihouseGate](
	[nCharNo] [int] NOT NULL,
	[nItemID] [int] NOT NULL,
	[bType] [tinyint] NOT NULL,
	[dDate] [datetime] NOT NULL,
	[dEndDate] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nItemID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tMinihouseGuest]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tMinihouseGuest](
	[nArticleNo] [int] IDENTITY(1,1) NOT NULL,
	[nCharNo] [int] NOT NULL,
	[nWriterNo] [int] NOT NULL,
	[sWriterID] [nvarchar](40) NOT NULL,
	[sContent] [nvarchar](1000) NOT NULL,
	[dDate] [datetime] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nArticleNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tPrison]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tPrison](
	[nPrisonNum] [bigint] IDENTITY(1,1) NOT NULL,
	[nCharID] [int] NOT NULL,
	[dPrisonDate] [datetime] NOT NULL,
	[nMinute] [smallint] NOT NULL,
	[sReason] [nvarchar](16) NULL,
	[nRegNumber] [bigint] NULL,
	[sGmID] [nvarchar](16) NULL,
	[sRemark] [nvarchar](64) NULL,
	[sRegenMapName] [nvarchar](16) NOT NULL,
	[nRegenX] [int] NOT NULL,
	[nRegenY] [int] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nPrisonNum] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tQuest]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tQuest](
	[nCharNo] [int] NOT NULL,
	[nQuestNo] [int] NOT NULL,
	[nStatus] [tinyint] NOT NULL,
	[sData] [varbinary](100) NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nQuestNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
/****** Object:  Table [dbo].[tSkill]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tSkill](
	[nCharNo] [int] NOT NULL,
	[nSkillNo] [smallint] NOT NULL,
	[nSkillLevel] [tinyint] NOT NULL DEFAULT ((1)),
	[nSkillExp] [int] NOT NULL DEFAULT ((0)),
	[nSkillWriteTime] [bigint] NOT NULL DEFAULT ((0)),
	[nSkillCoolTime] [int] NOT NULL DEFAULT ((0)),
	[nSkillPowerDemage] [tinyint] NOT NULL DEFAULT ((0)),
	[nSkillPowerSP] [tinyint] NOT NULL DEFAULT ((0)),
	[nSkillPowerKeepTime] [tinyint] NOT NULL DEFAULT ((0)),
	[nSkillPowerCoolTime] [tinyint] NOT NULL DEFAULT ((0)),
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC,
	[nSkillNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tSpamBlockTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tSpamBlockTime](
	[nCharNo] [int] NOT NULL,
	[sys_create_date] [datetime] NOT NULL,
	[sys_update_date] [datetime] NULL,
	[nBlockTime] [int] NOT NULL,
	[nStandbyTime] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nCharNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tSpamFilter]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tSpamFilter](
	[nUserNo] [int] NOT NULL,
	[sys_create_date] [datetime] NOT NULL,
	[sys_update_date] [datetime] NULL,
	[bIsSpamSpread] [bit] NOT NULL,
	[bIsSpamBlock] [bit] NOT NULL,
	[nSpamFilterRate] [tinyint] NOT NULL,
PRIMARY KEY CLUSTERED 
(
	[nUserNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tStatisticsGameMoney]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tStatisticsGameMoney](
	[nRowNo] [bigint] IDENTITY(1,1) NOT NULL,
	[dDate] [datetime] NOT NULL,
	[sCode] [nvarchar](20) NOT NULL,
	[nMoney] [bigint] NOT NULL,
PRIMARY KEY NONCLUSTERED 
(
	[nRowNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tUserMoney]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tUserMoney](
	[nUserNo] [int] NOT NULL,
	[nUserMoney] [bigint] NOT NULL DEFAULT ((0)),
PRIMARY KEY CLUSTERED 
(
	[nUserNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  View [dbo].[VT_CHAR]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[VT_CHAR] AS 
SELECT   dbo.tCharacter.nCharNo AS CharNo, dbo.tCharacter.sID AS CharID, 
                dbo.tCharacter.nUserNo AS UserNo, dbo.tCharacter.nAdminLevel AS AdminLevel, 
                dbo.tCharacter.nPS AS PS, dbo.tCharacter.nGS AS GS, 
                dbo.tCharacter.dCreateDate AS CreateDate, dbo.tCharacter.bDeleted AS IsDel, 
                dbo.tCharacter.nLoginZoneX AS X, dbo.tCharacter.nLoginZoneY AS Y, 
                dbo.tCharacter.dDeletedDate AS DeletedDate, dbo.tCharacter.nAP AS AP, 
                dbo.tCharacter.sLoginZone AS Zone, dbo.tCharacter.nLevel AS Lvl, 
                dbo.tCharacter.nExp AS Experience, dbo.tCharacter.nSlotNo AS SlotNo, 
                dbo.tCharacter.nHP AS HP, dbo.tCharacter.nSP AS SP, 
                dbo.tCharacter.nHPS AS HPS, dbo.tCharacter.nSPS AS SPS, 
                dbo.tCharacter.dLastLoginDate AS LogDate, 
                dbo.tCharacter.nLoginCount AS LogCount, dbo.tCharacter.nCreateWorld AS World, 
                dbo.tCharacter.nPlayMin AS PlayTime, dbo.tCharacter.nFlags AS Flags, 
                dbo.tCharacter.nMoney AS Money, dbo.tCharacterShape.nClass AS Class, 
                dbo.tCharacterShape.nRace AS Race, dbo.tCharacterShape.nGender AS Sex, 
                dbo.tCharacterShape.nHairType AS HairType, 
                dbo.tCharacterShape.nHairColor AS HairColor, 
                dbo.tCharacterShape.nFaceShape AS Face
FROM      dbo.tCharacter INNER JOIN
                dbo.tCharacterShape ON dbo.tCharacter.nCharNo = dbo.tCharacterShape.nCharNo

GO
/****** Object:  View [dbo].[VT_ITEM]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[VT_ITEM] AS 
SELECT   TOP 100 PERCENT dbo.tItem.nOwner AS Owner, 
                dbo.tItem.nStorageType AS StorageType, dbo.tItem.nStorage AS Storage, 
                dbo.tItem.nItemKey AS Itemkey, dbo.tItem.nItemID AS ItemID, 
                dbo.tItemOptions.nOptionType AS OptionType, 
                dbo.tItemOptions.nOptionData AS OptionData, dbo.tItemMobList.nMobID AS MobID, 
                dbo.tItemMobList.nGrade AS MobGrade, dbo.tItemMobList.nKillCount AS MobKillCount, 
                dbo.tItemTitle.nTitleType AS TitleType, dbo.tItemTitle.sTitle AS TitleName, 
                dbo.tItemTitle.nTitleCharNo AS TitleCreator, dbo.tItem.dDate AS CreateDate, 
                dbo.tItem.nFlags AS Flags
FROM      dbo.tItem LEFT OUTER JOIN
                dbo.tItemMobList ON 
                dbo.tItem.nItemKey = dbo.tItemMobList.nItemKey LEFT OUTER JOIN
                dbo.tItemTitle ON dbo.tItem.nItemKey = dbo.tItemTitle.nItemKey LEFT OUTER JOIN
                dbo.tItemOptions ON dbo.tItem.nItemKey = dbo.tItemOptions.nItemKey
GROUP BY dbo.tItem.nOwner, dbo.tItem.nStorageType, dbo.tItem.nStorage, 
                dbo.tItem.nItemKey, dbo.tItem.nItemID, dbo.tItemOptions.nOptionType, 
                dbo.tItemOptions.nOptionData, dbo.tItemMobList.nMobID, 
                dbo.tItemMobList.nGrade, dbo.tItemMobList.nKillCount, dbo.tItemTitle.nTitleType, 
                dbo.tItemTitle.sTitle, dbo.tItemTitle.nTitleCharNo, dbo.tItem.dDate, 
                dbo.tItem.nFlags
ORDER BY dbo.tItem.nOwner, dbo.tItem.nStorageType, dbo.tItem.nStorage, 
                dbo.tItem.nItemKey, dbo.tItem.nItemID, dbo.tItemOptions.nOptionType, 
                dbo.tItemOptions.nOptionData, dbo.tItemMobList.nMobID, 
                dbo.tItemMobList.nGrade, dbo.tItemMobList.nKillCount, dbo.tItemTitle.nTitleType, 
                dbo.tItemTitle.sTitle, dbo.tItemTitle.nTitleCharNo, dbo.tItem.dDate, 
                dbo.tItem.nFlags

GO
/****** Object:  View [dbo].[VT_ITEM_BRIF]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[VT_ITEM_BRIF] AS 
SELECT   TOP 100 PERCENT dbo.tItem.nOwner AS 소유자, 
                dbo.tItem.nStorageType AS 인벤종류, dbo.tItem.nStorage AS 인벤위치, 
                dbo.tItem.nItemKey AS 아템키, dbo.tItem.nItemID AS 아템아뒤, 
                dbo.tItemTitle.nTitleType AS 타이틀타입, dbo.tItemTitle.sTitle AS 타이틀, 
                dbo.tItemTitle.nTitleCharNo AS 타이틀부여자, dbo.tItem.dDate AS 만든날, 
                dbo.tItem.nFlags AS 예비정보
FROM      dbo.tItem LEFT OUTER JOIN
                dbo.tItemTitle ON dbo.tItem.nItemKey = dbo.tItemTitle.nItemKey
ORDER BY dbo.tItem.nOwner, dbo.tItem.nStorageType, dbo.tItem.nStorage, 
                dbo.tItem.nItemKey, dbo.tItem.nItemID, dbo.tItemTitle.nTitleType, 
                dbo.tItemTitle.sTitle, dbo.tItemTitle.nTitleCharNo, dbo.tItem.dDate, 
                dbo.tItem.nFlags

GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_tCharacter_sID_NC]    Script Date: 12/20/2015 6:11:00 PM ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_tCharacter_sID_NC] ON [dbo].[tCharacter]
(
	[sID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
SET ANSI_PADDING ON

GO
/****** Object:  Index [IX_tGuild_Name_NC]    Script Date: 12/20/2015 6:11:00 PM ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_tGuild_Name_NC] ON [dbo].[tGuild]
(
	[sName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE [dbo].[tAuction] ADD  DEFAULT (getdate()) FOR [sys_create_date]
GO
ALTER TABLE [dbo].[tAuction] ADD  DEFAULT (getdate()) FOR [dSellStartDate]
GO
ALTER TABLE [dbo].[tAuction] ADD  DEFAULT ((0)) FOR [nStatus]
GO
ALTER TABLE [dbo].[tAuctionInventory] ADD  DEFAULT (getdate()) FOR [sys_create_date]
GO
ALTER TABLE [dbo].[tAuctionInventory] ADD  DEFAULT (getdate()) FOR [dStartDate]
GO
ALTER TABLE [dbo].[tAuctionInventory] ADD  DEFAULT ((0)) FOR [bIsDelete]
GO
ALTER TABLE [dbo].[tCharacterChangeID] ADD  DEFAULT (getdate()) FOR [sys_create_date]
GO
ALTER TABLE [dbo].[tCharacterChangeID] ADD  DEFAULT ((0)) FOR [bFlag]
GO
ALTER TABLE [dbo].[tCharacterChangeID] ADD  DEFAULT ((0)) FOR [bInit]
GO
ALTER TABLE [dbo].[tCharacterChargedBuffer] ADD  DEFAULT ((0)) FOR [nID]
GO
ALTER TABLE [dbo].[tCharacterLoading] ADD  DEFAULT (getdate()) FOR [dDBTime]
GO
ALTER TABLE [dbo].[tChatBlock] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tCollectionCard] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tCollectionFavorites] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tCollectionReward] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tCollectionSerialCount] ADD  DEFAULT (getdate()) FOR [sys_create_date]
GO
ALTER TABLE [dbo].[tDice] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tDicePayLog] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tFriend] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tGambleCoin] ADD  DEFAULT ((0)) FOR [nCoin]
GO
ALTER TABLE [dbo].[tGambleCoin] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tGambleCoinExchangeLog] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tGambleCoinExchangeLog] ADD  DEFAULT ((0)) FOR [nBeforeCoin]
GO
ALTER TABLE [dbo].[tGambleCoinExchangeLog] ADD  DEFAULT ((0)) FOR [nAfterCoin]
GO
ALTER TABLE [dbo].[tGambleCoinExchangeLog] ADD  DEFAULT ((0)) FOR [nBeforeMoney]
GO
ALTER TABLE [dbo].[tGambleCoinExchangeLog] ADD  DEFAULT ((0)) FOR [nAfterMoney]
GO
ALTER TABLE [dbo].[tGambleDice] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tGambleDiceLog] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tGambleDiceResult] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tGambleJackpot] ADD  DEFAULT (getdate()) FOR [sys_create_date]
GO
ALTER TABLE [dbo].[tGambleJackpot] ADD  DEFAULT (getdate()) FOR [sys_update_date]
GO
ALTER TABLE [dbo].[tGambleJackpot] ADD  DEFAULT ((0)) FOR [nJackpotCoin]
GO
ALTER TABLE [dbo].[tGambleJackpotLog] ADD  DEFAULT ((0)) FOR [nJackpotCoin]
GO
ALTER TABLE [dbo].[tGambleSlotMachineLog] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tGambleSlotMachineLog] ADD  DEFAULT ((0)) FOR [nPrizeCoin]
GO
ALTER TABLE [dbo].[tGuildAcademyGraduate] ADD  DEFAULT (getdate()) FOR [dJoinDate]
GO
ALTER TABLE [dbo].[tGuildAcademyGraduate] ADD  DEFAULT (getdate()) FOR [dGraduateDate]
GO
ALTER TABLE [dbo].[tGuildAcademyMember] ADD  DEFAULT (getdate()) FOR [dJoinDate]
GO
ALTER TABLE [dbo].[tGuildAcademyMember] ADD  DEFAULT ((255)) FOR [nGrade]
GO
ALTER TABLE [dbo].[tGuildAcademyMember] ADD  DEFAULT ((0)) FOR [nChatBanTime]
GO
ALTER TABLE [dbo].[tGuildAcademyRanking] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tGuildTournamentRegist] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tGuildTournamentRegist] ADD  DEFAULT ((0)) FOR [nSeed]
GO
ALTER TABLE [dbo].[tGuildTournamentRegist] ADD  DEFAULT ((0)) FOR [bChoice]
GO
ALTER TABLE [dbo].[tGuildTournamentRegist] ADD  DEFAULT ((0)) FOR [bRefundNotice]
GO
ALTER TABLE [dbo].[tHolyPromise] ADD  DEFAULT (getdate()) FOR [dRegDate]
GO
ALTER TABLE [dbo].[tHolyPromise] ADD  DEFAULT (getdate()) FOR [dRejoinableDate]
GO
ALTER TABLE [dbo].[tHolyPromise] ADD  DEFAULT (getdate()) FOR [dMemberAcceptableDate]
GO
ALTER TABLE [dbo].[tHolyPromiseReward] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tInstanceDungeonCount] ADD  DEFAULT ((0)) FOR [nCount]
GO
ALTER TABLE [dbo].[tItemActionCoolTime] ADD  DEFAULT (getdate()) FOR [sys_create_date]
GO
ALTER TABLE [dbo].[tItemMobList] ADD  DEFAULT ((1)) FOR [nGrade]
GO
ALTER TABLE [dbo].[tItemMobList] ADD  DEFAULT ((0)) FOR [nKillCount]
GO
ALTER TABLE [dbo].[tItemTitle] ADD  DEFAULT ((0)) FOR [nTitleType]
GO
ALTER TABLE [dbo].[tItemTitle] ADD  DEFAULT ((0)) FOR [nTitleCharNo]
GO
ALTER TABLE [dbo].[tLog_GuildMasterChange] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tMinihouse] ADD  DEFAULT ((0)) FOR [nVisitor]
GO
ALTER TABLE [dbo].[tMinihouse] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tMinihouseGate] ADD  DEFAULT ((1)) FOR [bType]
GO
ALTER TABLE [dbo].[tMinihouseGate] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tMinihouseGuest] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tPrison] ADD  DEFAULT (getdate()) FOR [dPrisonDate]
GO
ALTER TABLE [dbo].[tPrison] ADD  DEFAULT ((0)) FOR [nRegNumber]
GO
ALTER TABLE [dbo].[tPrison] ADD  DEFAULT ('') FOR [sRegenMapName]
GO
ALTER TABLE [dbo].[tPrison] ADD  DEFAULT ((0)) FOR [nRegenX]
GO
ALTER TABLE [dbo].[tPrison] ADD  DEFAULT ((0)) FOR [nRegenY]
GO
ALTER TABLE [dbo].[tSpamBlockTime] ADD  DEFAULT (getdate()) FOR [sys_create_date]
GO
ALTER TABLE [dbo].[tSpamBlockTime] ADD  DEFAULT ((0)) FOR [nBlockTime]
GO
ALTER TABLE [dbo].[tSpamBlockTime] ADD  DEFAULT ((0)) FOR [nStandbyTime]
GO
ALTER TABLE [dbo].[tSpamFilter] ADD  DEFAULT (getdate()) FOR [sys_create_date]
GO
ALTER TABLE [dbo].[tSpamFilter] ADD  DEFAULT ((0)) FOR [bIsSpamSpread]
GO
ALTER TABLE [dbo].[tSpamFilter] ADD  DEFAULT ((0)) FOR [bIsSpamBlock]
GO
ALTER TABLE [dbo].[tSpamFilter] ADD  DEFAULT ((100)) FOR [nSpamFilterRate]
GO
ALTER TABLE [dbo].[tStatisticsGameMoney] ADD  DEFAULT (getdate()) FOR [dDate]
GO
ALTER TABLE [dbo].[tStatisticsGameMoney] ADD  DEFAULT ((0)) FOR [nMoney]
GO
ALTER TABLE [dbo].[tAuction]  WITH CHECK ADD FOREIGN KEY([nBidderNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tAuction]  WITH CHECK ADD FOREIGN KEY([nCategoryNo])
REFERENCES [dbo].[tAuctionCategory] ([nCategoryNo])
GO
ALTER TABLE [dbo].[tAuction]  WITH CHECK ADD FOREIGN KEY([nSellerNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tAuctionInventory]  WITH CHECK ADD FOREIGN KEY([nAuctionNo])
REFERENCES [dbo].[tAuction] ([nAuctionNo])
GO
ALTER TABLE [dbo].[tAuctionInventory]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tCharacterChangeID]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tCharacterChargedBuffer]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tCharacterDisposition]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tCharacterGameOption]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tCharacterGameOption]  WITH CHECK ADD FOREIGN KEY([nOptionNo])
REFERENCES [dbo].[tGameOptionInit] ([nOptionNo])
GO
ALTER TABLE [dbo].[tCharacterKeyMap]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tCharacterKeyMap]  WITH CHECK ADD FOREIGN KEY([nFunctionNo])
REFERENCES [dbo].[tKeyMapInit] ([nFunctionNo])
GO
ALTER TABLE [dbo].[tCharacterLoadingDetailInfo]  WITH CHECK ADD FOREIGN KEY([nCharNo], [nSeqNo])
REFERENCES [dbo].[tCharacterLoading] ([nCharNo], [nSeqNo])
GO
ALTER TABLE [dbo].[tCharacterOptions]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tCharacterShape]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tCharacterShortCut]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tCharacterSingleOption]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tCharacterState]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tCharacterTitle]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tChatBlock]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tCollectionCard]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tCollectionFavorites]  WITH CHECK ADD FOREIGN KEY([nCharNo], [nCardID])
REFERENCES [dbo].[tCollectionCard] ([nCharNo], [nCardID])
GO
ALTER TABLE [dbo].[tDice]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tDiceLog]  WITH CHECK ADD FOREIGN KEY([nGameNo], [nCustomCharNo])
REFERENCES [dbo].[tDiceResult] ([nGameNo], [nCustomCharNo])
GO
ALTER TABLE [dbo].[tDicePayLog]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tDiceResult]  WITH CHECK ADD FOREIGN KEY([nCustomCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tDiceResult]  WITH CHECK ADD FOREIGN KEY([nGameNo])
REFERENCES [dbo].[tDice] ([nGameNo])
GO
ALTER TABLE [dbo].[tFriend]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tGambleCoin]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tGambleDiceLog]  WITH CHECK ADD FOREIGN KEY([nGameNo], [nCharNo])
REFERENCES [dbo].[tGambleDiceResult] ([nGameNo], [nCharNo])
GO
ALTER TABLE [dbo].[tGambleDiceResult]  WITH CHECK ADD FOREIGN KEY([nGameNo])
REFERENCES [dbo].[tGambleDice] ([nGameNo])
GO
ALTER TABLE [dbo].[tGambleJackpotLog]  WITH CHECK ADD FOREIGN KEY([nGameNo])
REFERENCES [dbo].[tGambleSlotMachineLog] ([nGameNo])
GO
ALTER TABLE [dbo].[tGambleSlotMachineLog]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tGuildAcademy]  WITH CHECK ADD FOREIGN KEY([nMasterCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tGuildAcademy]  WITH CHECK ADD FOREIGN KEY([nNo])
REFERENCES [dbo].[tGuild] ([nNo])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tGuildAcademyMember]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tGuildAcademyMember]  WITH CHECK ADD FOREIGN KEY([nNo])
REFERENCES [dbo].[tGuildAcademy] ([nNo])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tGuildAcademyReward]  WITH CHECK ADD FOREIGN KEY([nTypeID])
REFERENCES [dbo].[tGuildAcademyRewardType] ([nTypeID])
GO
ALTER TABLE [dbo].[tGuildAcademyReward]  WITH CHECK ADD FOREIGN KEY([nNo])
REFERENCES [dbo].[tGuildAcademy] ([nNo])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tGuildMember]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tGuildMember]  WITH CHECK ADD FOREIGN KEY([nNo])
REFERENCES [dbo].[tGuild] ([nNo])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tGuildToken]  WITH CHECK ADD FOREIGN KEY([nNo])
REFERENCES [dbo].[tGuild] ([nNo])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tHolyPromise]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tHolyPromiseReward]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tItemActionCoolTime]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tItemEnchant]  WITH CHECK ADD FOREIGN KEY([nItemKey])
REFERENCES [dbo].[tItem] ([nItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tItemMobList]  WITH CHECK ADD FOREIGN KEY([nItemKey])
REFERENCES [dbo].[tItem] ([nItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tItemOptions]  WITH CHECK ADD FOREIGN KEY([nItemKey])
REFERENCES [dbo].[tItem] ([nItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tItemTitle]  WITH CHECK ADD FOREIGN KEY([nItemKey])
REFERENCES [dbo].[tItem] ([nItemKey])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[tMarriage]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tMinihouse]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tMinihouseGate]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tMinihouse] ([nCharNo])
GO
ALTER TABLE [dbo].[tMinihouseGuest]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tMinihouse] ([nCharNo])
GO
ALTER TABLE [dbo].[tPrison]  WITH CHECK ADD FOREIGN KEY([nCharID])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tQuest]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tSkill]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
ALTER TABLE [dbo].[tSpamBlockTime]  WITH CHECK ADD FOREIGN KEY([nCharNo])
REFERENCES [dbo].[tCharacter] ([nCharNo])
GO
/****** Object:  StoredProcedure [dbo].[p_Char_AddExp]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-04-07
@return	0		<성공>
	others		<실패>
@brief	케릭서 저장 프로시져화.
==================================================*/
CREATE PROCEDURE [dbo].[p_Char_AddExp]
@nCharNo int,
@nExp bigint
AS
SET NOCOUNT ON
UPDATE tCharacter 
	SET 
		nExp=nExp+@nExp
	WHERE nCharNo=@nCharNo
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Char_ChangeClass]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-04-07
@return	0		<성공>
	others		<실패>
@brief	케릭서 저장 프로시져화.
==================================================*/
CREATE PROCEDURE [dbo].[p_Char_ChangeClass]
@nCharNo int,
@nClass tinyint
AS
SET NOCOUNT ON
UPDATE tCharacterShape 
	SET 
		nClass=@nClass
	WHERE nCharNo=@nCharNo
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Char_ChangeID]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_ChangeID]
/*
Character change ID 
2004.9 By CJC
 input:
   See code
 output: 
   1 = ok
   0 = error
*/
@nCharNo int,
@sID nvarchar(40), 
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- Change Char ID
UPDATE tCharacter SET sID = @sID WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	SET @nRet = 0
	RETURN
END
-- success
SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_CheckOptionsExistance]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
-----------------------------------
SadPig : 2006.7.6 (OPTool)
	Input Parameter
		@nCharNo : Character No		
	Output Parameter
		@nRet		
		0 : Not Exist
		1 : Exist
-----------------------------------
*/
CREATE PROCEDURE [dbo].[p_Char_CheckOptionsExistance]
	@nCharNo		int,
	@nRet			int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000
	
	IF EXISTS(SELECT * FROM  tCharacterOptions WHERE nCharNo = @nCharNo )
		SET @nRet = 1
	ELSE
		SET @nRet = 0
	
	SET LOCK_TIMEOUT -1
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Create]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Character Create 
2004.6 By CJC
 input:
   All Args
 output: 
   nCharNo = 1~? 생성된 캐릭의 번호(에러시 = 0 )
           =  0 캐릭 생성 에러
           = -1 해당 유저의 슬롯에 캐릭이 있음.
           = -2 캐릭 외모 기록 에러
           = -3 캐릭 옵션 기록 에러
2010.10.7 By kodong
  신규 단축키 시스템 추가로 인한 프로시저 수정
*/
CREATE PROCEDURE [dbo].[p_Char_Create] 
	@nUserNo int,			-- 1	1 ~ ?
	@nCreateWorld tinyint,	-- 2	0 ~ ?
	@nAdminLevel tinyint,	-- 3	0=USER, 1~?=GM Level 1~?
	@nSlotNo tinyint,		-- 4	0 ~ 5
	@sID nvarchar(40),		-- 5  
	@nRace tinyint,			-- 6	0 = Human, 1 = Elf, 2 = Dark elf
	@nClass tinyint,		-- 7	1 = Fighter,4 = Cleric, 7 = Archer, 10 = Mage
	@nGender tinyint,		-- 8	0 = Male, 1 = Female
	@nHairType tinyint,		-- 9	0 ~ ?
	@nHairColor tinyint,	-- 10	0 ~ ?
	@nFaceShape tinyint,	-- 11	0 ~ ?
	@nCharNo int OUTPUT     -- 12
AS
BEGIN
	SET NOCOUNT ON
	-- 에러코드 일단 세팅
	SET @nCharNo = 0
	-- 해당유저의 해당슬롯에 캐릭이 있는지 확인
	IF EXISTS (SELECT nUserNo FROM tCharacter(NOLOCK) WHERE nUserNo = @nUserNo AND nSlotNo = @nSlotNo AND bDeleted = 0)
	BEGIN
		SET @nCharNo = -1
		RETURN
	END
	-- 캐릭 생성
	BEGIN TRAN
	INSERT tCharacter (  nUserNo,  nSlotNo,  sID,  nCreateWorld,  nAdminLevel )
	VALUES            ( @nUserNo, @nSlotNo, @sID, @nCreateWorld, @nAdminLevel )
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END
	SET @nCharNo = @@IDENTITY
	-- 캐릭 외모 세팅
	INSERT tCharacterShape (  nCharNo,  nRace,  nClass,  nGender,  nHairType,  nHairColor,  nFaceShape )
	VALUES                 ( @nCharNo, @nRace, @nClass, @nGender, @nHairType, @nHairColor, @nFaceShape ) 
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nCharNo = -2
		RETURN
	END
	-- 캐릭 옵션 세팅
	INSERT tCharacterOptions (  nCharNo )
	VALUES                   ( @nCharNo )
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nCharNo = -3
		RETURN
	END
	-- 캐릭 생성 성공

	-- 2010.10.7
	-- kodong
	-- 새로 추가된 단축키 시스템에 의해 초기값 지정
	DECLARE @nRet int
	SET @nRet = 0
	EXEC usp_Character_initKeyMap @nCharNo, @nRet output
	IF @@ERROR <> 0 OR @nRet <> 0 BEGIN
		ROLLBACK TRAN
		SET @nCharNo = -4
		RETURN
	END
	ELSE BEGIN
		COMMIT TRAN
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_CreateSetDefaultData]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_CreateSetDefaultData]
/*
Character Create set default data
2005.6 By CJC
 input:
   All args
   
 output: 
   0 = error
   1 = ok
*/
-- Character columns
@nCharNo int,
@sLoginZone varchar(16),
@nLoginZoneX int,
@nLoginZoneY int,
@nHP smallint, 
@nSP smallint, 
@nHPS smallint,
@nSPS smallint,
@nMoney bigint,
-- Output var
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacter SET
	sLoginZone	= @sLoginZone,
	nLoginZoneX	= @nLoginZoneX,
	nLoginZoneY	= @nLoginZoneY,
	nHP			= @nHP,
	nSP			= @nSP,
	nHPS		= @nHPS,
	nSPS		= @nSPS,
	nMoney		= @nMoney
WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	SET @nRet = 0
	RETURN
END
SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_DelChargedBuff]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_DelChargedBuff]
/*
Char Delete charged buff
2006.6 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nKey int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
DELETE FROM tCharacterChargedBuffer WHERE nCharNo = @nCharNo AND nKey = @nKey
SET @nRet = @@ERROR
RETURN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_DelCharTitle]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
'--------------------------------------------------------------------------------------
' 함수명 : p_Char_DelCharTitle
' 내  용 : OPTool 에서 사용. 지정된 캐릭터의 지정된 타이틀 삭제.
' 작성자 : 이병기
' 작성일 : 2005년 11월 25일
' 버  젼 : 1.0
' 인  자 :
'			input Parameter
'				@nCharNo		캐릭넘버
'				@nType			타이틀 타입, 
'				@nElementNo		타이틀 단계, 
'
'			Output Parameter
'				@nRet			tinyint OUTPUT
'				
'			RETURN_VALUE
'
'--------------------------------------------------------------------------------------
*/
CREATE PROCEDURE [dbo].[p_Char_DelCharTitle]
@nCharNo		int,
@nType			tinyint, 
@nElementNo		tinyint, 
@nRet			tinyint OUTPUT
AS
SET NOCOUNT ON
-- 해당 상태 삭제
DELETE FROM tCharacterTitle WHERE nCharNo = @nCharNo AND nType = @nType AND nElementNo = @nElementNo
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Delete]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Delete]
/*
Character Delete
2004.6 By CJC
  Input:
    nCharNo = Character number to be delete.
  Output:
    0 = Delete OK
    1 = 해당 캐릭이 이미 지워진 캐릭임
    2 = 해당 캐릭을 찾을수 없음
    3 = 해당 캐릭을 지울수 없음
  Desc:
    - 지워진 캐릭의 ID는 '아뒤~날짜#시도횟수' 형태로 바뀐다.
    - 버그 방지로 아뒤에는 '~'는 사용되면 안된다.
*/
@nCharNo int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 이미 지워진 캐릭인지 조사
IF EXISTS(SELECT nCharNo FROM tCharacter(NOLOCK) WHERE nCharNo = @nCharNo AND bDeleted > 0)
BEGIN
	SET @nRet = 1
	RETURN
END
-- 지워질 캐릭의 이름 얻기
DECLARE @sID nvarchar(40)
SET @sID = ''
SELECT @sID = sID FROM tCharacter(NOLOCK) WHERE nCharNo = @nCharNo
IF LEN(@sID) = 0
BEGIN
	SET @nRet = 2 -- 해당 캐릭이 없음
	RETURN
END
-- 아뒤내에 최초 삭제마크 이후의 문자는 모두 지운다.(지운거 또 지울수 있음으로 오류방지용)
DECLARE @DeleteMark nvarchar(2)
SET @DeleteMark = N'~'                       -- 삭제 마크 세팅
DECLARE @StartDeleteMark int
SET @StartDeleteMark = CHARINDEX( @DeleteMark, @sID )
IF @StartDeleteMark > 0
	SET @sID = LEFT( @sID, @StartDeleteMark-1 )
-- 지워질 캐릭의 ID를 변경
DECLARE @CurrentDate datetime
SET @CurrentDate = GETDATE()
DECLARE @nDeleteCount int
SET @nDeleteCount = 0
DECLARE @sChangedID nvarchar(40)
NAME_CHANGE: -- 이름 만들기 '아뒤' + 삭제마크 + '날짜' + '#시도횟수'
SET @sChangedID = 
	RTRIM(@sID) + 
	@DeleteMark + DATENAME(year, @CurrentDate) + DATENAME(month, @CurrentDate) + DATENAME(day, @CurrentDate) +
	N'#' + CAST( @nDeleteCount AS nvarchar(2) )
-- 캐릭 지우기
UPDATE tCharacter SET 
bDeleted = 1,
dDeletedDate = GETDATE(),
sID = @sChangedID
WHERE nCharNo = @nCharNo
-- 실패시 50번 이름을 바꾸면서 시도한다.
IF @@ERROR = 2601 -- 인덱스키 중복인 경우 
BEGIN
	SET @nDeleteCount = @nDeleteCount + 1
	IF @nDeleteCount < 50
		GOTO NAME_CHANGE
		
	-- 실패	
	SET @nRet = 3 
	RETURN
END	
-- 성공
SET @nRet = 0 
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_DelOptions]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
-----------------------------------
SadPig : 2006.7.6 (OPTool)
	Input Parameter
		@nCharNo : Character No		
	Output Parameter
		@nRet		
		0 : OK
		1-? : error code
-----------------------------------
*/
CREATE PROCEDURE [dbo].[p_Char_DelOptions]
	@nCharNo		int,
	@nRet			int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000
	
	DELETE FROM tCharacterOptions WHERE nCharNo = @nCharNo 
	SET @nRet = @@ERROR
	
	SET LOCK_TIMEOUT -1
	SET NOCOUNT OFF	
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_DelState]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_DelState]
/*
Char Delete state
2004.10 By CJC
 input:
	nCharNo, nStateNo = To be delete info.
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nStateNo smallint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 해당 상태 삭제
DELETE FROM tCharacterState WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_DelStateAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_DelStateAll]
/*
Char Delete state all
2004.10 By CJC
 input:
	nCharNo, nStateNo = To be delete info.
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 해당 상태 삭제
DELETE FROM tCharacterState WHERE nCharNo = @nCharNo
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_FameAdd]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_FameAdd]
/*
Add fame
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK
	        0 = Error
*/
@nCharNo int,
@nAddFame int,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
DECLARE @nCharFame int
EXEC p_Char_FameGet @nCharNo, @nCharFame OUTPUT, @nRet OUTPUT
IF @nRet = 0
	RETURN
-- Add fame
SET @nCharFame = @nCharFame + @nAddFame
EXEC p_Char_FameSet @nCharNo, @nCharFame, @nRet OUTPUT
-- End


GO
/****** Object:  StoredProcedure [dbo].[p_Char_FameGet]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_FameGet]
/*
Get fame
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK, Fame return
	        0 = Error
*/
@nCharNo int,
@nCharFame int OUTPUT,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
SET @nRet = 0
-- Get fame
SELECT @nCharFame = nFame FROM tCharacter WHERE nCharNo = @nCharNo
IF @@ROWCOUNT = 1
	SET @nRet = 1
	
-- End
RETURN


GO
/****** Object:  StoredProcedure [dbo].[p_Char_FameSet]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_FameSet]
/*
Set fame
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK
	        0 = Error
*/
@nCharNo int,
@nSetFame int,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tCharacter SET nFame = @nSetFame WHERE nCharNo = @nCharNo
IF @@ERROR = 0 AND @@ROWCOUNT = 1
	SET @nRet = 1
-- end
RETURN


GO
/****** Object:  StoredProcedure [dbo].[p_Char_FameSub]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_FameSub]
/*
Sub fame
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK
	        0 = Error, or Minus value
*/
@nCharNo int,
@nSubFame int,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
DECLARE @nCharFame int
EXEC p_Char_FameGet @nCharNo, @nCharFame OUTPUT, @nRet OUTPUT
IF @nRet = 0
	RETURN
-- Sub fame
SET @nCharFame = @nCharFame - @nSubFame
-- Check minus
IF @nCharFame < 0
BEGIN
	SET @nRet = 0
	RETURN	
END
EXEC p_Char_FameSet @nCharNo, @nCharFame, @nRet OUTPUT
-- End


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Find]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Find]
/*
Character Find
2004.6 By CJC
  input:
    sID = 찾을 ID
  output:
    0 = 없음
    1~? = 찾은 캐릭번호
*/
@sID nvarchar(40),
@nCharNo int OUTPUT
AS
SET NOCOUNT ON
SET @nCharNo = 0
SELECT @nCharNo = nCharNo FROM tCharacter(NOLOCK) WHERE sID = @sID
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetAllData]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetAllData]
/*
Character Get all data
2004.6 By CJC
 input:
   nCharNo = To be get login data
 output:
	none
 desc:
	fetch success, get data
	fetch fail, not data
*/
@nCharNo int
AS
SET NOCOUNT ON
SELECT
nUserNo,
nSlotNo,
sID,
nLevel,
nExp,
nHP,
nSP,
nAP,
nHPS,
nSPS,
nPS,
nGS,
nMoney,
nFame,
nFlags,
nAdminLevel,
sLoginZone,
nLoginZoneX,
nLoginZoneY,
nLoginZoneD,
nPrisonMin,
nPKCount,
nPKYellowTime,
nStrength,
nConstitute,
nDexterity,
nIntelligence,
nMentalPower,
nRedistributePoint,
nPlayMin,
nLoginCount,
dLastLoginDate,
dCreateDate,
nCreateWorld,
bDeleted,
dDeletedDate
FROM tCharacter
WHERE nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetChargedBufferAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetChargedBufferAll]
/*
Char Get charaged buffer all
2006.6 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int
AS
SET NOCOUNT ON
SELECT nKey, nID, dUseDate, dEndDate
FROM tCharacterChargedBuffer WHERE nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetChargedBufferCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetChargedBufferCount]
/*
Char Get charaged buffer all count
2006.6 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int,
@nCount int OUTPUT
AS
SET NOCOUNT ON
SELECT @nCount = COUNT(*) FROM tCharacterChargedBuffer WHERE nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetCharID]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetCharID]
/*
Get Char ID by Char No
input: CharNo
Output:
    @nRet, 0 = Not found char
           1 = @sID, Found char ID
*/
@nCharNo int,
@sID nvarchar(40) OUTPUT,
@nRet int OUTPUT
AS
SET NOCOUNT ON
SELECT @sID = sID FROM tCharacter WHERE nCharNo = @nCharNo
SET @nRet = @@ROWCOUNT
-- END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetCharNo]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetCharNo]
/*
Get Char No by Char ID
Input: sID
Output:
    @nCharNo, 0 = Not found user
              ? = Found user No
*/
@sID nvarchar(40),
@nCharNo int OUTPUT
AS
SET NOCOUNT ON
SET @nCharNo = 0
SELECT @nCharNo = nCharNo FROM tCharacter WHERE sID = @sID
-- END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetIsDeleted]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
'--------------------------------------------------------------------------------------
' 함수명 : p_Char_GetIsDeleted
' 내  용 : 삭제된 캐릭인지 확인.
' 작성자 : 이병기
' 작성일 : 2005년 10월 25일
' 버  젼 : 1.0
' 인  자 :
'			input Parameter
'				@nCharNo	: 캐릭번호
'           output 
'				@nRet		: 0 = 삭제되지 않음
'                             1 = 삭제됨
'--------------------------------------------------------------------------------------
*/
CREATE PROCEDURE [dbo].[p_Char_GetIsDeleted]
@nCharNo int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
IF EXISTS(SELECT nCharNo FROM tCharacter(NOLOCK) WHERE nCharNo = @nCharNo AND bDeleted > 0)
BEGIN
	SET @nRet = 1
		RETURN
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetKQMap]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetKQMap]
/*
Character Get Kingdom quest map
2006.4 By CJC
 input:
   nCharNo = To be get KQ Map data
 output:
	none
 desc:
	fetch success, get data
	fetch fail, not data
*/
@nCharNo int
AS
SET NOCOUNT ON
SELECT
nKQHandle,
sKQMap,
nKQX,
nKQY,
nKQD,
dKQDate
FROM tCharacter
WHERE nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetListOfUserChar]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetListOfUserChar]
/*
Character Get list of user character
2004.6 By CJC
  Input:
    nUserNo = Search user's character
  output: 
	none
 desc:
	fetch success, get data
	fetch fail, not data
*/
@nUserNo int
AS
SET NOCOUNT ON
SELECT nCharNo FROM tCharacter(NOLOCK) WHERE nUserNo = @nUserNo AND bDeleted = 0
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetListOfUserCharAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetListOfUserCharAll]
/*
Character Get list of user character(include deleted character)
2004.6 By CJC
  Input:
    nUserNo = Search user's character
  output: 
	none
 desc:
	fetch success, get data
	fetch fail, not data
*/
@nUserNo int
AS
SET NOCOUNT ON
SELECT nCharNo FROM tCharacter(NOLOCK) WHERE nUserNo = @nUserNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetLoginData]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetLoginData]
/*
Character Get login data
2004.6 By CJC
 input:
	nCharNo = To be get login data
 output:
	none
 desc:
	fetch success, get data
	fetch fail, not data
*/
@nCharNo int
AS
SET NOCOUNT ON
SELECT 
	C.sID, 
	C.nLevel, 
	C.nSlotNo, 
	C.sLoginZone, 
	C.bDeleted, 
	C.dDeletedDate,
	
	S.nRace, 
	S.nClass, 
	S.nGender, 
	S.nHairType, 
	S.nHairColor, 
	S.nFaceShape,
	
	C.nKQHandle,
	C.sKQMap,
	C.nKQX,
	C.nKQY,
	C.nKQD,
	C.dKQDate
FROM tCharacter AS C
INNER JOIN tCharacterShape AS S ON S.nCharNo = @nCharNo
WHERE C.nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetNumOfUserChar]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetNumOfUserChar]
/*
Character number of user character
2004.6 By CJC
  Input:
    nUserNo = Search user's character
  output: 
    0 = none
    ? = number of user's character, execpt deleted.
*/
@nUserNo int,
@nNumOfUserChar int OUTPUT
AS
SET NOCOUNT ON
SET @nNumOfUserChar = 0
SELECT @nNumOfUserChar = COUNT(nCharNo) FROM tCharacter(NOLOCK) WHERE nUserNo = @nUserNo AND bDeleted = 0
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetNumOfUserCharAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetNumOfUserCharAll]
/*
Character number of user character(include deleted character)
2004.6 By CJC
  Input:
    nUserNo = Search user's character
  output: 
    0 = none
    ? = number of user's character
*/
@nUserNo int,
@nNumOfUserChar int OUTPUT
AS
SET NOCOUNT ON
SET @nNumOfUserChar = 0
SELECT @nNumOfUserChar = COUNT(nCharNo) FROM tCharacter(NOLOCK) WHERE nUserNo = @nUserNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetOptGame]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetOptGame]
/*
Character Get options
2005.8 By CJC
 input:
   nCharNo = To be get option data
 output:
	@sData = Option binary data
*/
@nCharNo int,
@nRet tinyint output,
@sData varbinary(64) output
AS
SET NOCOUNT ON
SET @nRet = 0
SELECT @sData = sGame, @nRet = 1 FROM tCharacterOptions WHERE nCharNo = @nCharNo AND sGame IS NOT NULL
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetOptKeyMapping]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetOptKeyMapping]
/*
Character Get options
2005.8 By CJC
 input:
   nCharNo = To be get option data
 output:
	@sData = Option binary data
*/
@nCharNo int,
@nRet tinyint output,
@sData varbinary(308) output
AS
SET NOCOUNT ON
SET @nRet = 0
SELECT @sData = sKeyMapping, @nRet = 1 FROM tCharacterOptions WHERE nCharNo = @nCharNo AND sKeyMapping IS NOT NULL
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetOptShortCutData]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetOptShortCutData]
/*
Character Get options
2005.8 By CJC
 input:
   nCharNo = To be get option data
 output:
	@sData = Option binary data
*/
@nCharNo int,
@nRet tinyint output,
@sData varbinary(1024) output
AS
SET NOCOUNT ON
SET @nRet = 0
SELECT @sData = sShortCutData, @nRet = 1 FROM tCharacterOptions WHERE nCharNo = @nCharNo AND sShortCutData IS NOT NULL
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetOptShortCutSize]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetOptShortCutSize]
/*
Character Get options
2005.8 By CJC
 input:
   nCharNo = To be get option data
 output:
	@sData = Option binary data
*/
@nCharNo int,
@nRet tinyint output,
@sData varbinary(24) output
AS
SET NOCOUNT ON
SET @nRet = 0
SELECT @sData = sShortCutSize, @nRet = 1 FROM tCharacterOptions WHERE nCharNo = @nCharNo AND sShortCutSize IS NOT NULL
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetOptSound]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetOptSound]
/*
Character Get options
2005.8 By CJC
 input:
   nCharNo = To be get option data
 output:
	@sData = Option binary data
*/
@nCharNo int,
@nRet tinyint output,
@sData varbinary(1) output
AS
SET NOCOUNT ON
SET @nRet = 0
SELECT @sData = sSound, @nRet = 1 FROM tCharacterOptions WHERE nCharNo = @nCharNo AND sSound IS NOT NULL
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetOptVideo]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetOptVideo]
/*
Character Get options
2005.8 By CJC
 input:
   nCharNo = To be get option data
 output:
	@sData = Option binary data
*/
@nCharNo int,
@nRet tinyint output,
@sData varbinary(60) output
AS
SET NOCOUNT ON
SET @nRet = 0
SELECT @sData = sVideo, @nRet = 1 FROM tCharacterOptions WHERE nCharNo = @nCharNo AND sVideo IS NOT NULL
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetOptWindowsPos]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetOptWindowsPos]
/*
Character Get options
2005.8 By CJC
 input:
   nCharNo = To be get option data
 output:
	@sData = Option binary data
*/
@nCharNo int,
@nRet tinyint output,
@sData varbinary(392) output
AS
SET NOCOUNT ON
SET @nRet = 0
SELECT @sData = sWindowsPos, @nRet = 1 FROM tCharacterOptions WHERE nCharNo = @nCharNo AND sWindowsPos IS NOT NULL
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetShape]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetShape]
/*
Character Get shape
2004.6 By CJC
 input:
   nCharNo = To be get shape
 output:
	none
 desc:
	fetch success, get data
	fetch fail, not data
*/
@nCharNo int
AS
SET NOCOUNT ON
SELECT 
	nRace, 
	nClass, 
	nGender, 
	nHairType, 
	nHairColor, 
	nFaceShape 
FROM tCharacterShape WHERE nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetState]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Get state 
2004.10 By CJC
 input:
	see SQL
 output:
	@nRet	0 = No data found
	        ? = Number data here(must to be 1)
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)		        
*/
CREATE PROCEDURE [dbo].[p_Char_GetState]
	@nCharNo int,
	@nStateNo smallint,
	@nStateLevel smallint OUTPUT,
	@nStateTime int OUTPUT,
	@nStateCount smallint OUTPUT,
	@nStatePowerDemage tinyint OUTPUT,
	@nStatePowerSP tinyint OUTPUT,
	@nStatePowerKeepTime tinyint OUTPUT,
	@nStatePowerCoolTime tinyint OUTPUT,
	@nCasterLevel smallint output,
	@nCasterAttackPower int output,		
	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON

	SELECT 
		@nStateLevel         = nStateLevel, 
		@nStateTime          = nStateTime,
		@nStateCount         = nStateCount,	
		@nStatePowerDemage   = nStatePowerDemage,
		@nStatePowerSP       = nStatePowerSP,
		@nStatePowerKeepTime = nStatePowerKeepTime,
		@nStatePowerCoolTime = nStatePowerCoolTime,
		@nCasterLevel        = nCasterLevel,
		@nCasterAttackPower  = @nCasterAttackPower 
	  FROM tCharacterState 
	 WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo
	SET @nRet = @@ROWCOUNT
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetStateAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Get state all
2004.10 By CJC
 input:
	see SQL
 output:
	fetch to take data
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)		
*/
CREATE PROCEDURE [dbo].[p_Char_GetStateAll]
	@nCharNo int
AS
BEGIN
	SET NOCOUNT ON
	SELECT 
		nStateNo, 
		nStateLevel, 
		nStateTime,
		nStateCount,
		nStatePowerDemage,
		nStatePowerSP,
		nStatePowerKeepTime,
		nStatePowerCoolTime,
		nCasterLevel,
		nCasterAttackPower 
	 FROM tCharacterState 
	WHERE nCharNo = @nCharNo
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetStateAllWithRestTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Get state all
2009.05.15 By temlost
 input:
	see SQL
 output:
	fetch to take data
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)		
*/
CREATE PROCEDURE [dbo].[p_Char_GetStateAllWithRestTime]
	@nCharNo int
AS
BEGIN
	SET NOCOUNT ON
	SELECT 
		nStateNo, 
		nStateLevel, 
		nStateTime,
		nRestTime,
		nStateCount,
		nStatePowerDemage,
		nStatePowerSP,
		nStatePowerKeepTime,
		nStatePowerCoolTime,
		nCasterLevel,
		nCasterAttackPower 		
	 FROM tCharacterState 
	WHERE nCharNo = @nCharNo
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetStateAllWithSetItem]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Get state all With SetItem
2008.06 By Lunar
 input:
	see SQL
 output:
	fetch to take data
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)		
*/
CREATE PROCEDURE [dbo].[p_Char_GetStateAllWithSetItem]
	@nCharNo int
AS
BEGIN
	SET NOCOUNT ON
	SELECT 
		nStateNo, 
		nStateLevel, 
		nStateTime,
		nStateCount,
		nStatePowerDemage,
		nStatePowerSP,
		nStatePowerKeepTime,
		nStatePowerCoolTime,
		nSetItemIndexA,
		nSetItemValueA,
		nSetItemIndexB,
		nSetItemValueB,
		nSetItemIndexC,
		nSetItemValueC,
		nSetItemIndexD,
		nSetItemValueD,
		nCasterLevel,
		nCasterAttackPower		
	 FROM tCharacterState 
	WHERE nCharNo = @nCharNo
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetStateAllWithSetItemAndRestTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Get state all With SetItem
2009.05.15 By temlost
 input:
	see SQL
 output:
	fetch to take data
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)		
*/
CREATE PROCEDURE [dbo].[p_Char_GetStateAllWithSetItemAndRestTime]
	@nCharNo int
AS
BEGIN
	SET NOCOUNT ON
	SELECT 
		nStateNo, 
		nStateLevel, 
		nStateTime,
		nRestTime,
		nStateCount,
		nStatePowerDemage,
		nStatePowerSP,
		nStatePowerKeepTime,
		nStatePowerCoolTime,
		nSetItemIndexA,
		nSetItemValueA,
		nSetItemIndexB,
		nSetItemValueB,
		nSetItemIndexC,
		nSetItemValueC,
		nSetItemIndexD,
		nSetItemValueD,
		nCasterLevel,
		nCasterAttackPower
	 FROM tCharacterState 
	WHERE nCharNo = @nCharNo
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetStateWithRestTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Get state all With SetItem
2009.05.15 By temlost
 input:
	see SQL
 output:
	fetch to take data
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)		
*/
CREATE PROCEDURE [dbo].[p_Char_GetStateWithRestTime]
	@nCharNo int,
	@nStateNo smallint,
	@nStateLevel smallint OUTPUT,
	@nStateTime int OUTPUT,
	@nRestTime int OUTPUT,
	@nStateCount smallint OUTPUT,
	@nStatePowerDemage tinyint OUTPUT,
	@nStatePowerSP tinyint OUTPUT,
	@nStatePowerKeepTime tinyint OUTPUT,
	@nStatePowerCoolTime tinyint OUTPUT,
	@nCasterLevel smallint output,
	@nCasterAttackPower int output,			
	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT 
		@nStateLevel			= nStateLevel, 
		@nStateTime			= nStateTime,
		@nRestTime			= nRestTime,
		@nStateCount			= nStateCount,	
		@nStatePowerDemage		= nStatePowerDemage,
		@nStatePowerSP			= nStatePowerSP,
		@nStatePowerKeepTime	= nStatePowerKeepTime,
		@nStatePowerCoolTime	= nStatePowerCoolTime,
		@nCasterLevel        = nCasterLevel,
		@nCasterAttackPower  = @nCasterAttackPower 		
	  FROM tCharacterState 
	 WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo

	SET @nRet = @@ROWCOUNT
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetStateWithSetItem]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Get state 
2004.10 By CJC
 input:
	see SQL
 output:
	@nRet	0 = No data found
	        ? = Number data here(must to be 1)
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)		        
*/
CREATE PROCEDURE [dbo].[p_Char_GetStateWithSetItem]
	@nCharNo int,
	@nStateNo smallint,
	@nStateLevel smallint OUTPUT,
	@nStateTime int OUTPUT,
	@nStateCount smallint OUTPUT,
	@nStatePowerDemage tinyint OUTPUT,
	@nStatePowerSP tinyint OUTPUT,
	@nStatePowerKeepTime tinyint OUTPUT,
	@nStatePowerCoolTime tinyint OUTPUT,
	@nSetItemIndexA smallint OUTPUT,
	@nSetItemValueA smallint OUTPUT,
	@nSetItemIndexB smallint OUTPUT,
	@nSetItemValueB smallint OUTPUT,
	@nSetItemIndexC smallint OUTPUT,
	@nSetItemValueC smallint OUTPUT,
	@nSetItemIndexD smallint OUTPUT,
	@nSetItemValueD smallint OUTPUT,
	@nCasterLevel smallint output,
	@nCasterAttackPower int output,			
	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT 
		@nStateLevel			= nStateLevel, 
		@nStateTime			= nStateTime,
		@nStateCount			= nStateCount,	
		@nStatePowerDemage		= nStatePowerDemage,
		@nStatePowerSP		= nStatePowerSP,
		@nStatePowerKeepTime	= nStatePowerKeepTime,
		@nStatePowerCoolTime		= nStatePowerCoolTime,
		@nSetItemIndexA		= nSetItemIndexA,
		@nSetItemValueA		= nSetItemValueA,
		@nSetItemIndexB		= nSetItemIndexB,
		@nSetItemValueB		= nSetItemValueB,
		@nSetItemIndexC		= nSetItemIndexC,
		@nSetItemValueC		= nSetItemValueC,
		@nSetItemIndexD		= nSetItemIndexD,
		@nSetItemValueD		= nSetItemValueD,
		@nCasterLevel        = nCasterLevel,
		@nCasterAttackPower  = @nCasterAttackPower 		
	  FROM tCharacterState 
 	 WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo

	SET @nRet = @@ROWCOUNT
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetStateWithSetItemAndRestTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Get state With Settime And RestTime
2009.05 By temlost
 input:
	see SQL
 output:
	@nRet	0 = No data found
	        ? = Number data here(must to be 1)
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)		        
*/
CREATE PROCEDURE [dbo].[p_Char_GetStateWithSetItemAndRestTime]
	@nCharNo int,
	@nStateNo smallint,
	@nStateLevel smallint OUTPUT,
	@nStateTime int OUTPUT,
	@nRestTime int OUTPUT,
	@nStateCount smallint OUTPUT,
	@nStatePowerDemage tinyint OUTPUT,
	@nStatePowerSP tinyint OUTPUT,
	@nStatePowerKeepTime tinyint OUTPUT,
	@nStatePowerCoolTime tinyint OUTPUT,
	@nSetItemIndexA smallint OUTPUT,
	@nSetItemValueA smallint OUTPUT,
	@nSetItemIndexB smallint OUTPUT,
	@nSetItemValueB smallint OUTPUT,
	@nSetItemIndexC smallint OUTPUT,
	@nSetItemValueC smallint OUTPUT,
	@nSetItemIndexD smallint OUTPUT,
	@nSetItemValueD smallint OUTPUT,
	@nCasterLevel smallint output,
	@nCasterAttackPower int output,			
	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT 
		@nStateLevel			= nStateLevel, 
		@nStateTime			= nStateTime,
		@nRestTime			= nRestTime,
		@nStateCount			= nStateCount,	
		@nStatePowerDemage		= nStatePowerDemage,
		@nStatePowerSP		= nStatePowerSP,
		@nStatePowerKeepTime	= nStatePowerKeepTime,
		@nStatePowerCoolTime		= nStatePowerCoolTime,
		@nSetItemIndexA		= nSetItemIndexA,
		@nSetItemValueA		= nSetItemValueA,
		@nSetItemIndexB		= nSetItemIndexB,
		@nSetItemValueB		= nSetItemValueB,
		@nSetItemIndexC		= nSetItemIndexC,
		@nSetItemValueC		= nSetItemValueC,
		@nSetItemIndexD		= nSetItemIndexD,
		@nSetItemValueD		= nSetItemValueD,
		@nCasterLevel        = nCasterLevel,
		@nCasterAttackPower  = @nCasterAttackPower 		
	  FROM tCharacterState 
	 WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo

	SET @nRet = @@ROWCOUNT
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetTitleAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetTitleAll]
/*
Character title set
2005.10 By CJC
  Input:
    nCharNo = character number
  output: 
    featch to get data
*/
@nCharNo int
AS
SET NOCOUNT ON
SELECT nType, nElementNo, nElementValue 
  FROM tCharacterTitle WITH(READUNCOMMITTED)
 WHERE nCharNo = @nCharNo ORDER BY nNo  
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetTitleCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetTitleCount]
/*
Character number of title
2005.10 By CJC
  Input:
    nCharNo = character number
  output: 
    0 = none
    ? = number of title on this character
*/
@nCharNo int,
@nCount int OUTPUT
AS
SET NOCOUNT ON
SET @nCount = 0
SELECT @nCount = COUNT(*) FROM tCharacterTitle(NOLOCK) WHERE nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_GetUserNo]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_GetUserNo]
/*
Get User No by Char ID
Input: nCharNo
Output:
    @nUserNo, 0 = Not found user
              ? = Found user No
*/
@nCharNo int,
@nUserNo int OUTPUT
AS
SET NOCOUNT ON
SET @nUserNo = 0
SELECT @nUserNo = nUserNo FROM tCharacter WHERE nCharNo = @nCharNo
-- END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Login]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 개체: 저장 프로시저 dbo.p_Char_Login 스크립트 날짜: 2007-03-13 오후 6:25:10 ******/


CREATE PROCEDURE [dbo].[p_Char_Login]
/*
Character login
2004.6 By CJC
Updated: 2012.5 By Korv4kx
Updated: 2015.7 By Regie
Input:
nCharNo = To be login
DB Output: Fills LoggedInChars with more info.
Output:
0 = error
1 = work ok
*/
@nCharNo int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacter
SET nLoginCount = nLoginCount + 1,
dLastLoginDate = GETDATE()
WHERE nCharNo = @nCharNo
SET @nRet = @@ROWCOUNT
INSERT INTO dbo.LoggedInChars (nCharNo) VALUES (@nCharNo)
UPDATE dbo.LoggedInChars
SET nUserNo = dbo.tCharacter.nUserNo,
nAdminLevel = dbo.tCharacter.nAdminLevel,
sID = dbo.tCharacter.sID,
sLoginZone = dbo.tCharacter.sLoginZone,
nLoginCount = dbo.tCharacter.nLoginCount,
nPlayMin = dbo.tCharacter.nPlayMin,
nLevel = dbo.tCharacter.nLevel,
nExp = dbo.tCharacter.nExp,
nFame = dbo.tCharacter.nFame,
nMoney = dbo.tCharacter.nMoney
FROM dbo.tCharacter
WHERE dbo.LoggedInChars.nCharNo = dbo.tCharacter.nCharNo
UPDATE dbo.LoggedInChars
SET nClass = dbo.tCharacterShape.nClass
FROM dbo.tCharacterShape
WHERE dbo.LoggedInChars.nCharNo = dbo.tCharacterShape.nCharNo
UPDATE dbo.LoggedInChars
SET nCoin = dbo.tGambleCoin.nCoin
FROM dbo.tGambleCoin
WHERE dbo.LoggedInChars.nCharNo = dbo.tGambleCoin.nCharNo
RETURN
-- end
GO
/****** Object:  StoredProcedure [dbo].[p_Char_Logout]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** 개체: 저장 프로시저 dbo.p_Char_Logout 스크립트 날짜: 2007-03-13 오후 6:25:10 ******/


CREATE PROCEDURE [dbo].[p_Char_Logout]
/*
Character logout
2004.6 By CJC
Input:
nCharNo = To be logout
nPlayMin = Play minute at this time
output:
0 = error
1 = work ok
*/
@nCharNo int,
@nPlayMin int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacter
SET nPlayMin = nPlayMin + @nPlayMin
WHERE nCharNo = @nCharNo
SET @nRet = @@ROWCOUNT
Delete from dbo.LoggedInChars where nCharNo = @nCharNo
-- end
GO
/****** Object:  StoredProcedure [dbo].[p_Char_MoneyAdd]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_MoneyAdd]
/*
Add money
2004.8 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK
	        0 = Error
*/
@nCharNo int,
@nAddMoney bigint,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
DECLARE @nCharMoney bigint
EXEC p_Char_MoneyGet @nCharNo, @nCharMoney OUTPUT, @nRet OUTPUT
IF @nRet = 0
	RETURN
-- Add money
SET @nCharMoney = @nCharMoney + @nAddMoney
EXEC p_Char_MoneySet @nCharNo, @nCharMoney, @nRet OUTPUT
-- End


GO
/****** Object:  StoredProcedure [dbo].[p_Char_MoneyGet]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_MoneyGet]
/*
Get money
2004.8 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK, Money return
	        0 = Error
*/
@nCharNo int,
@nCharMoney bigint OUTPUT,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
SET @nRet = 0
-- 돈 얻기
SELECT @nCharMoney = nMoney FROM tCharacter WHERE nCharNo = @nCharNo
IF @@ROWCOUNT = 1
	SET @nRet = 1
	
-- End
RETURN


GO
/****** Object:  StoredProcedure [dbo].[p_Char_MoneyGetCharsByUserNo]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
-----------------------------------
SadPig : 2006.9.5 (OPTool)
	Input Parameter
		@nMoney : Money
	Output Parameter
		int nCharNo;
		char sCharID[40];
		__int64 nMoney;
		WORD nLevel;
		BYTE nSlotNo;
		BYTE bDeleted;
		BYTE nAdminLevel;
-----------------------------------
*/
CREATE PROCEDURE [dbo].[p_Char_MoneyGetCharsByUserNo]
	@nUserNo		int
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000
	SELECT nCharNo, sID, nMoney, nLevel, nSlotNo, bDeleted, nAdminLevel 
	FROM tCharacter WHERE nUserNo =  @nUserNo
	
	SET LOCK_TIMEOUT -1
	SET NOCOUNT OFF	
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_MoneyGetGreaterThen]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
-----------------------------------
SadPig : 2006.9.5 (OPTool)
	Input Parameter
		@nMoney : Money
	Output Parameter
		int nUserNo;
		int nCharNo;
		char sCharID[40];
		__int64 nMoney;
		WORD nLevel;
		BYTE nSlotNo;
		BYTE bDeleted;
		BYTE nAdminLevel;
-----------------------------------
*/
CREATE PROCEDURE [dbo].[p_Char_MoneyGetGreaterThen]
	@nMoney		bigint
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000
	SELECT nUserNo, nCharNo, sID, nMoney, nLevel, nSlotNo, bDeleted, nAdminLevel 
	FROM tCharacter WHERE nMoney >=  @nMoney
	
	SET LOCK_TIMEOUT -1
	SET NOCOUNT OFF	
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_MoneyMove]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_MoneyMove]
/*
Move money
2008.2 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK
	        0 = Error
*/
	@nCharNoFrom int,
	@nCharNoTo   int,
	@nMoveMoney  bigint,
	@nRet        tinyint OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	IF @nMoveMoney < 0
		BEGIN
			SET @nRet = 0
			RETURN
		END
	IF @nMoveMoney = 0
		BEGIN
			SET @nRet = 1
			RETURN
		END
		
	DECLARE @money as bigint
	BEGIN TRAN
	IF NOT EXISTS(SELECT nCharNo FROM tCharacter WHERE nCharNo = @nCharNoFrom AND bDeleted = 0)
	BEGIN
		SET @nRet = 0
		ROLLBACK TRAN
		RETURN
	END
	IF NOT EXISTS(SELECT nCharNo FROM tCharacter WHERE nCharNo = @nCharNoTo AND bDeleted = 0)
	BEGIN
		SET @nRet = 0
		ROLLBACK TRAN
		RETURN
	END
	SELECT @money = nMoney FROM tCharacter WHERE nCharNo = @nCharNoFrom AND bDeleted = 0
	IF @money >= @nMoveMoney
		BEGIN
			-- SUB MONEY
			UPDATE tCharacter SET nMoney = @money - @nMoveMoney WHERE nCharNo = @nCharNoFrom AND bDeleted = 0
			IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
			BEGIN
				SET @nRet =0
				ROLLBACK TRAN
				RETURN
			END
			
			-- ADD MONEY
			UPDATE tCharacter SET nMoney = nMoney + @nMoveMoney WHERE nCharNo = @nCharNoTo AND bDeleted = 0
			IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
			BEGIN
				SET @nRet = 0
				ROLLBACK TRAN
				RETURN
			END
	
			SET @nRet = 1
			COMMIT TRAN
		END
	ELSE
		BEGIN
			SET @nRet = 0
			ROLLBACK TRAN
			RETURN
		END
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_MoneySet]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_MoneySet]
/*
Set money
2004.8 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK
	        0 = Error
*/
@nCharNo int,
@nSetMoney bigint,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tCharacter SET nMoney = @nSetMoney WHERE nCharNo = @nCharNo
IF @@ERROR = 0 AND @@ROWCOUNT = 1
	SET @nRet = 1
-- end
RETURN


GO
/****** Object:  StoredProcedure [dbo].[p_Char_MoneySub]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_MoneySub]
/*
Sub money
2004.8 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK
	        0 = Error, or Minus value
*/
@nCharNo int,
@nSubMoney bigint,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
DECLARE @nCharMoney bigint
EXEC p_Char_MoneyGet @nCharNo, @nCharMoney OUTPUT, @nRet OUTPUT
IF @nRet = 0
	RETURN
-- Sub money
SET @nCharMoney = @nCharMoney - @nSubMoney
-- Check minus
IF @nCharMoney < 0
BEGIN
	SET @nRet = 0
	RETURN	
END
EXEC p_Char_MoneySet @nCharNo, @nCharMoney, @nRet OUTPUT
-- End


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Rename]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Rename]
/*
Char Rename
2006.9 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@sID nvarchar(40),
-- Output var
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacter SET sID = @sID WHERE nCharNo = @nCharNo
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SaveLevelExpFrame]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-04-07
@return	0		<성공>
	others		<실패>
@brief	케릭서 저장 프로시져화.
==================================================*/
CREATE PROCEDURE [dbo].[p_Char_SaveLevelExpFrame] 
@nCharNo int,
@nLevel smallint,
@nExp bigint,
@nFame int
AS
SET NOCOUNT ON
UPDATE tCharacter 
	SET 
		nLevel=@nLevel,
		nExp=@nExp,
		nFame=@nFame
	WHERE nCharNo=@nCharNo
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SaveLocation]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-04-07
@return	0		<성공>
	others		<실패>
@brief	케릭서 저장 프로시져화.
==================================================*/
CREATE PROCEDURE [dbo].[p_Char_SaveLocation] 
@nCharNo		int,
@sLoginZone		nvarchar(16),
@nLoginZoneX	int,
@nLoginZoneY	int,
@nKQHandle		int,
@sKQMap			nvarchar(16),
@nKQX			int,
@nKQY			int
AS
SET NOCOUNT ON
UPDATE tCharacter SET 
	sLoginZone=@sLoginZone,
	nLoginZoneX=@nLoginZoneX,
	nLoginZoneY=@nLoginZoneY,
	
	nKQHandle=@nKQHandle,
	sKQMap=@sKQMap,
	nKQX=@nKQX,
	nKQY=@nKQY,
	dKQDate=GetDate()
	WHERE nCharNo=@nCharNo
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SavePKCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SavePKCount] 
/*
Character Set nPKCount
2007.2 By CJC
 input:
   All args
 output: 
   @@error
*/
@nCharNo int,
@nPKCount int
AS
SET NOCOUNT ON
UPDATE tCharacter SET nPKCount=@nPKCount WHERE nCharNo=@nCharNo
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SaveStat]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-04-07
@return	0		<성공>
	others		<실패>
@brief	케릭서 저장 프로시져화.
==================================================*/
CREATE PROCEDURE [dbo].[p_Char_SaveStat] 
@nCharNo int,
@nPS int,
@nGS int,
@nHPS smallint,
@nSPS smallint,
@nHP smallint,
@nSP smallint
AS
SET NOCOUNT ON
UPDATE tCharacter 
	SET 
		nPS=@nPS,
		nGS=@nGS,
		nHPS=@nHPS,
		nSPS=@nSPS,
		nHP=@nHP,
		nSP=@nSP 
	WHERE nCharNo=@nCharNo
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetAdminLevel]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
'--------------------------------------------------------------------------------------
' 함수명 : p_Char_SetAdminLevel
' 내  용 : 레벨과 경험치를 수정하는 프로시쥬어
' 작성자 : 이병기
' 작성일 : 2006년 02월 28일
' 버  젼 : 1.0
' 인  자 :
'			input Parameter
'				@nCharNo	: 캐릭터 넘버
'				@nAdmin		: 운영자 캐릭 세팅 여부
'			Output Parameter
'				@RET 	: 결과
					= 1		: 성공
'					= 0 	: 실패
'--------------------------------------------------------------------------------------
*/
CREATE PROCEDURE [dbo].[p_Char_SetAdminLevel]
@nCharNo	int,
@nAdmin		Tinyint,
@nRet		int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacter SET 
	nAdminLevel			= @nAdmin
WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	SET @nRet = 0
	RETURN
END
SET @nRet = 1


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetAllData]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SetAllData]
/*
Character Set all data
2004.6 By CJC
 input:
   All args
 output: 
   1 = update ok
   0 = error at update chatacter data
*/
-- Character columns
@nCharNo int,
@nUserNo int, 
@nSlotNo tinyint,
@sID nvarchar(40), 
@nLevel smallint, 
@nExp bigint, 
@nHP smallint, 
@nSP smallint, 
@nAP smallint, 
@nHPS smallint,
@nSPS smallint,
@nPS int,
@nGS int,
@nMoney bigint,
@nFame int, 
@nFlags int, 
@nAdminLevel tinyint, 
@sLoginZone varchar(16),
@nLoginZoneX int,
@nLoginZoneY int,
@nLoginZoneD tinyint,
@nPrisonMin smallint, 
@nPKCount int, 
@nPKYellowTime tinyint,
@nStrength tinyint,
@nConstitute tinyint,
@nDexterity tinyint,
@nIntelligence tinyint,
@nMentalPower tinyint,
@nRedistributePoint tinyint,
@nPlayMin int, 
@nLoginCount int, 
@dLastLoginDate datetime, 
@dCreateDate datetime, 
@nCreateWorld tinyint, 
@bDeleted tinyint, 
@dDeletedDate datetime,
-- Output var
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- Update character
UPDATE tCharacter SET
	nUserNo		=	@nUserNo , 
	nSlotNo			=	@nSlotNo , 
	sID			=	@sID , 
	nLevel			=	@nLevel , 
	nExp			=	@nExp , 
	nHP			=	@nHP , 
	nSP			=	@nSP , 
	nAP			=	@nAP , 
	nHPS			=	@nHPS , 
	nSPS			=	@nSPS , 
	nPS 			=	@nPS,
	nGS			=	@nGS,
	
	nMoney			= 	@nMoney , 
	nFame			= 	@nFame , 
	nFlags			= 	@nFlags , 
	nAdminLevel		=	@nAdminLevel ,
	
	sLoginZone		=	@sLoginZone , 
	nLoginZoneX		=	@nLoginZoneX , 
	nLoginZoneY		=	@nLoginZoneY , 
	nLoginZoneD		=	@nLoginZoneD ,
	
	nPrisonMin		=	@nPrisonMin , 
	nPKCount		=	@nPKCount , 
	nPKYellowTime		=	@nPKYellowTime ,
	
	nStrength		= 	@nStrength,
	nConstitute		= 	@nConstitute,
	nDexterity		= 	@nDexterity,
	nIntelligence		= 	@nIntelligence,
	nMentalPower		= 	@nMentalPower,
	nRedistributePoint	= 	@nRedistributePoint,
	
	nPlayMin		=	@nPlayMin , 
	nLoginCount		=	@nLoginCount , 
	dLastLoginDate		=	@dLastLoginDate ,
	
	dCreateDate		=	@dCreateDate , 
	nCreateWorld		=	@nCreateWorld ,
	bDeleted		=	@bDeleted, 
	dDeletedDate		=	@dDeletedDate 
WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	SET @nRet = 0
	RETURN
END
-- Update success
SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetChargedBuffer]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SetChargedBuffer]
/*
Char Set charged buffer
2006.6 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nKey int,
@nID smallint,
@dUseDate datetime,
@dEndDate datetime,
@nRet int OUTPUT
AS
SET NOCOUNT ON
IF EXISTS(SELECT nCharNo FROM tCharacterChargedBuffer WHERE nCharNo = @nCharNo AND nKey = @nKey )
BEGIN
	UPDATE tCharacterChargedBuffer SET 
		nID = @nID,
		dUseDate = @dUseDate,
		dEndDate = @dEndDate
	WHERE nCharNo = @nCharNo AND nKey = @nKey
END
ELSE
BEGIN
	INSERT tCharacterChargedBuffer (  nCharNo,  nKey,  nID,  dUseDate,  dEndDate )
	VALUES                         ( @nCharNo, @nKey, @nID, @dUseDate, @dEndDate )
END
SET @nRet = @@ERROR
RETURN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetLevelExp]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
'--------------------------------------------------------------------------------------
' 함수명 : p_Char_SetLevelExp
' 내  용 : 레벨과 경험치를 수정하는 프로시쥬어
' 작성자 : 이병기
' 작성일 : 2005년 10월 08일
' 버  젼 : 1.0
' 인  자 :
'			input Parameter
'				@nCharNo	: 캐릭터 넘버
'				@nLevel		: 레벨
'				@nExp		: 경험치
'			Output Parameter
'				@RET 	: 결과
					= 1		: 성공
'					= 0 	: 실패
'--------------------------------------------------------------------------------------
*/
CREATE PROCEDURE [dbo].[p_Char_SetLevelExp]
@nCharNo	int,
@nLevel		smallint,
@nExp		bigint,
@nRet		int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacter SET 
	nLevel			= @nLevel,
	nExp			= @nExp
WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	SET @nRet = 0
	RETURN
END
SET @nRet = 1


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetOptGame]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SetOptGame]
/*
Character Set options
2004.6 By CJC
 input:
   All args
 output: 
   0 = error
   1 = update ok
*/
@nCharNo int,
@sData varbinary(64),
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacterOptions SET sGame = @sData WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tCharacterOptions ( nCharNo, sGame ) VALUES ( @nCharNo, @sData )
	SET @nRet = @@ROWCOUNT
	RETURN
END
SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetOptKeyMapping]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SetOptKeyMapping]
/*
Character Set options
2004.6 By CJC
 input:
   All args
 output: 
   0 = error
   1 = update ok
*/
@nCharNo int,
@sData varbinary(308),
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacterOptions SET sKeyMapping = @sData WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tCharacterOptions (nCharNo, sKeyMapping) VALUES (@nCharNo, @sData)
	SET @nRet = @@ROWCOUNT
	RETURN
END
SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetOptShortCutData]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SetOptShortCutData]
/*
Character Set options
2004.6 By CJC
 input:
   All args
 output: 
   0 = error
   1 = update ok
*/
@nCharNo int,
@sData varbinary(1024),
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacterOptions SET sShortCutData = @sData WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tCharacterOptions (nCharNo, sShortCutData) VALUES (@nCharNo, @sData)
	SET @nRet = @@ROWCOUNT
	RETURN
END
SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetOptShortCutSize]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SetOptShortCutSize]
/*
Character Set options
2004.6 By CJC
 input:
   All args
 output: 
   0 = error
   1 = update ok
*/
@nCharNo int,
@sData varbinary(24),
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacterOptions SET sShortCutSize = @sData WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tCharacterOptions (nCharNo, sShortCutSize) VALUES (@nCharNo, @sData)
	SET @nRet = @@ROWCOUNT
	RETURN
END
SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetOptSound]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SetOptSound]
/*
Character Set options
2004.6 By CJC
 input:
   All args
 output: 
   0 = error
   1 = update ok
*/
@nCharNo int,
@sData varbinary(1),
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacterOptions SET sSound = @sData WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tCharacterOptions (nCharNo, sSound) VALUES (@nCharNo, @sData)
	SET @nRet = @@ROWCOUNT
	RETURN
END
SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetOptVideo]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SetOptVideo]
/*
Character Set options
2004.6 By CJC
 input:
   All args
 output: 
   0 = error
   1 = update ok
*/
@nCharNo int,
@sData varbinary(60),
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacterOptions SET sVideo = @sData WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tCharacterOptions (nCharNo, sVideo) VALUES (@nCharNo, @sData)
	SET @nRet = @@ROWCOUNT
	RETURN
END
SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetOptWindowsPos]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SetOptWindowsPos]
/*
Character Set options
2004.6 By CJC
 input:
   All args
 output: 
   0 = error
   1 = update ok
*/
@nCharNo int,
@sData varbinary(392),
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacterOptions SET sWindowsPos = @sData WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tCharacterOptions (nCharNo, sWindowsPos) VALUES (@nCharNo, @sData)
	SET @nRet = @@ROWCOUNT
	RETURN
END
SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetShape]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SetShape]
/*
Character Set shape
2004.6 By CJC
 input:
   All args
 output: 
   0 = error
   1 = update ok
*/
@nCharNo int,
@nRace tinyint, 
@nClass tinyint, 
@nGender tinyint, 
@nHairType tinyint, 
@nHairColor tinyint, 
@nFaceShape tinyint, 
-- Output var
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
UPDATE tCharacterShape SET
	nRace		= @nRace,
	nClass		= @nClass,
	nGender		= @nGender,
	nHairType	= @nHairType,
	nHairColor	= @nHairColor,
	nFaceShape	= @nFaceShape
WHERE nCharNo = @nCharNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	SET @nRet = 0
	RETURN
END
SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetState]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Set state
2004.10 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)	        
*/
CREATE PROCEDURE [dbo].[p_Char_SetState]
	@nCharNo int,
	@nStateNo smallint,
	@nStateLevel smallint,
	@nStateTime int,
	@nStateCount smallint,
	@nStatePowerDemage tinyint,
	@nStatePowerSP tinyint,
	@nStatePowerKeepTime tinyint,
	@nStatePowerCoolTime tinyint,
	@nCasterLevel smallint,
	@nCasterAttackPower int,
	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	IF EXISTS(SELECT nCharNo FROM tCharacterState WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo ) BEGIN
		UPDATE tCharacterState 
		   SET 
			nStateLevel			= @nStateLevel,
			nStateTime			= @nStateTime,
			nStateCount			= @nStateCount,	
			nStatePowerDemage	= @nStatePowerDemage,
			nStatePowerSP		= @nStatePowerSP,
			nStatePowerKeepTime	= @nStatePowerKeepTime,
			nStatePowerCoolTime	= @nStatePowerCoolTime,
		    nCasterLevel         = @nCasterLevel,
		    nCasterAttackPower   = @nCasterAttackPower 				
		WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo
		
		SET @nRet = @@ERROR
	END
	ELSE BEGIN
		INSERT tCharacterState (  nCharNo,  nStateNo,  nStateLevel,  nStateTime,  nStateCount,  nStatePowerDemage,  nStatePowerSP,  nStatePowerKeepTime,  nStatePowerCoolTime, nCasterLevel, nCasterAttackPower )
		VALUES                 ( @nCharNo, @nStateNo, @nStateLevel, @nStateTime, @nStateCount, @nStatePowerDemage, @nStatePowerSP, @nStatePowerKeepTime, @nStatePowerCoolTime, @nCasterLevel, @nCasterAttackPower )

		SET @nRet = @@ERROR
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetStateWithRestTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Set state
2004.10 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)		        
*/
CREATE PROCEDURE [dbo].[p_Char_SetStateWithRestTime]
	@nCharNo int,
	@nStateNo smallint,
	@nStateLevel smallint,
	@nStateTime int,
	@nRestTime int,
	@nStateCount smallint,
	@nStatePowerDemage tinyint,
	@nStatePowerSP tinyint,
	@nStatePowerKeepTime tinyint,
	@nStatePowerCoolTime tinyint,
	@nCasterLevel smallint,
	@nCasterAttackPower int,	
	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON

	IF EXISTS(SELECT nCharNo FROM tCharacterState WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo ) BEGIN
		UPDATE tCharacterState SET 
			nStateLevel			= @nStateLevel,
			nStateTime			= @nStateTime,
			nRestTime			= @nRestTime,
			nStateCount			= @nStateCount,	
			nStatePowerDemage	= @nStatePowerDemage,
			nStatePowerSP		= @nStatePowerSP,
			nStatePowerKeepTime	= @nStatePowerKeepTime,
			nStatePowerCoolTime	= @nStatePowerCoolTime,
		    nCasterLevel         = @nCasterLevel,
		    nCasterAttackPower   = @nCasterAttackPower 					
		WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo
		
		SET @nRet = @@ERROR
	END
	ELSE BEGIN
		INSERT tCharacterState (  nCharNo,  nStateNo,  nStateLevel,  nStateTime, nRestTime,  nStateCount,  nStatePowerDemage,  nStatePowerSP,  nStatePowerKeepTime,  nStatePowerCoolTime, nCasterLevel, nCasterAttackPower )
		VALUES                 ( @nCharNo, @nStateNo, @nStateLevel, @nStateTime, @nRestTime, @nStateCount, @nStatePowerDemage, @nStatePowerSP, @nStatePowerKeepTime, @nStatePowerCoolTime, @nCasterLevel, @nCasterAttackPower )

		SET @nRet = @@ERROR
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetStateWithSetItem]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Set state With SetItem
2008.06 By Lunar
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)		        
*/
CREATE PROCEDURE [dbo].[p_Char_SetStateWithSetItem]
	@nCharNo int,
	@nStateNo smallint,
	@nStateLevel smallint,
	@nStateTime int,
	@nStateCount smallint,
	@nStatePowerDemage tinyint,
	@nStatePowerSP tinyint,
	@nStatePowerKeepTime tinyint,
	@nStatePowerCoolTime tinyint,
	@nSetItemIndexA smallint,
	@nSetItemValueA smallint,
	@nSetItemIndexB smallint,
	@nSetItemValueB smallint,
	@nSetItemIndexC smallint,
	@nSetItemValueC smallint,
	@nSetItemIndexd smallint,
	@nSetItemValueD smallint,
	@nCasterLevel smallint,
	@nCasterAttackPower int,
	@nRet int = 0 OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	
	IF EXISTS(SELECT nCharNo FROM tCharacterState WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo) BEGIN
		UPDATE tCharacterState 
		   SET nStateLevel			= @nStateLevel
		     , nStateTime			= @nStateTime
		     , nStateCount			= @nStateCount
		     , nStatePowerDemage	= @nStatePowerDemage
		     , nStatePowerSP		= @nStatePowerSP
		     , nStatePowerKeepTime	= @nStatePowerKeepTime
		     , nStatePowerCoolTime	= @nStatePowerCoolTime
		     , nSetItemIndexA		= @nSetItemIndexA
		     , nSetItemValueA		= @nSetItemValueA
		     , nSetItemIndexB		= @nSetItemIndexB
		     , nSetItemValueB		= @nSetItemValueB
		     , nSetItemIndexC		= @nSetItemIndexC
		     , nSetItemValueC		= @nSetItemValueC
		     , nSetItemIndexD		= @nSetItemIndexD
		     , nSetItemValueD		= @nSetItemValueD
		     , nCasterLevel         = @nCasterLevel 
		     , nCasterAttackPower   = @nCasterAttackPower 
		 WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo

		SET @nRet = @@ERROR
	END
	ELSE BEGIN
		INSERT tCharacterState (nCharNo, nStateNo, nStateLevel, nStateTime, nStateCount, nStatePowerDemage, nStatePowerSP, nStatePowerKeepTime, nStatePowerCoolTime, nSetItemIndexA, nSetItemValueA, nSetItemIndexB, nSetItemValueB, nSetItemIndexC, nSetItemValueC, nSetItemIndexD, nSetItemValueD, nCasterLevel, nCasterAttackPower)
		VALUES (@nCharNo, @nStateNo, @nStateLevel, @nStateTime, @nStateCount, @nStatePowerDemage, @nStatePowerSP, @nStatePowerKeepTime, @nStatePowerCoolTime, @nSetItemIndexA, @nSetItemValueA, @nSetItemIndexB, @nSetItemValueB, @nSetItemIndexC, @nSetItemValueC, @nSetItemIndexD, @nSetItemValueD, @nCasterLevel, @nCasterAttackPower)

		SET @nRet = @@ERROR
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetStateWithSetItemAndRestTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Char Set state With SetItem
2008.06 By Lunar
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
2011.10.19 by kodong
  酒胆府酒 脚痹 胶懦(臂饭叼俊捞磐 : 盒畴狼 凯扁 / 饭牢历 : 气藕拳混) 包访
  脚痹拿烦蔼 眠啊(nCasterLevel, nCasterAttackPower)		        
*/
CREATE PROCEDURE [dbo].[p_Char_SetStateWithSetItemAndRestTime]
	@nCharNo int,
	@nStateNo smallint,
	@nStateLevel smallint,
	@nStateTime int,
	@nRestTime int,
	@nStateCount smallint,
	@nStatePowerDemage tinyint,
	@nStatePowerSP tinyint,
	@nStatePowerKeepTime tinyint,
	@nStatePowerCoolTime tinyint,
	@nSetItemIndexA smallint,
	@nSetItemValueA smallint,
	@nSetItemIndexB smallint,
	@nSetItemValueB smallint,
	@nSetItemIndexC smallint,
	@nSetItemValueC smallint,
	@nSetItemIndexd smallint,
	@nSetItemValueD smallint,
	@nCasterLevel smallint,
	@nCasterAttackPower int,
	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON

	IF EXISTS(SELECT nCharNo FROM tCharacterState WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo )
	BEGIN
		UPDATE tCharacterState SET 
			nStateLevel			= @nStateLevel,
			nStateTime			= @nStateTime,
			nRestTime			= @nRestTime,
			nStateCount			= @nStateCount,	
			nStatePowerDemage	= @nStatePowerDemage,
			nStatePowerSP		= @nStatePowerSP,
			nStatePowerKeepTime	= @nStatePowerKeepTime,
			nStatePowerCoolTime	= @nStatePowerCoolTime,
			nSetItemIndexA		= @nSetItemIndexA,
			nSetItemValueA		= @nSetItemValueA,
			nSetItemIndexB		= @nSetItemIndexB,
			nSetItemValueB		= @nSetItemValueB,
			nSetItemIndexC		= @nSetItemIndexC,
			nSetItemValueC		= @nSetItemValueC,
			nSetItemIndexD		= @nSetItemIndexD,
			nSetItemValueD		= @nSetItemValueD,
		    nCasterLevel        = @nCasterLevel,
		    nCasterAttackPower  = @nCasterAttackPower 			
		WHERE nCharNo = @nCharNo AND nStateNo = @nStateNo
		
		SET @nRet = @@ERROR
	END
	ELSE BEGIN
		INSERT tCharacterState (  nCharNo,  nStateNo,  nStateLevel,  nStateTime, nRestTime,  nStateCount,  nStatePowerDemage,  nStatePowerSP,  nStatePowerKeepTime,  nStatePowerCoolTime, nSetItemIndexA, nSetItemValueA, nSetItemIndexB, nSetItemValueB, nSetItemIndexC, nSetItemValueC, nSetItemIndexD, nSetItemValueD, nCasterLevel, nCasterAttackPower )
		VALUES                 ( @nCharNo, @nStateNo, @nStateLevel, @nStateTime, @nRestTime, @nStateCount, @nStatePowerDemage, @nStatePowerSP, @nStatePowerKeepTime, @nStatePowerCoolTime, @nSetItemIndexA, @nSetItemValueA, @nSetItemIndexB, @nSetItemValueB, @nSetItemIndexC, @nSetItemValueC, @nSetItemIndexD, @nSetItemValueD, @nCasterLevel, @nCasterAttackPower )

		SET @nRet = @@ERROR
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SetTitle]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_SetTitle]
/*
Character Set shape
2004.6 By CJC
 input:
   All args
 output: 
   0 = error
   1 = update/insert ok
*/
@nCharNo		int,
@nType			tinyint, 
@nElementNo		tinyint, 
@nElementValue	bigint,
@nRet			tinyint OUTPUT
AS
SET NOCOUNT ON
-- SET ERROR FIRST
SET @nRet = 0
IF EXISTS( SELECT nCharNo FROM tCharacterTitle WHERE nCharNo = @nCharNo AND nType = @nType AND nElementNo = @nElementNo )
BEGIN
	UPDATE tCharacterTitle SET nElementValue = @nElementValue
	WHERE nCharNo = @nCharNo AND nType = @nType AND nElementNo = @nElementNo
	IF @@ERROR = 0 AND @@ROWCOUNT = 1
	BEGIN
		SET @nRet = 1
		RETURN
	END
END
ELSE
BEGIN
	INSERT tCharacterTitle (  nCharNo,  nType,  nElementNo,  nElementValue )
	VALUES                 ( @nCharNo, @nType, @nElementNo, @nElementValue )
	IF @@ERROR = 0
	BEGIN
		SET @nRet = 1
		RETURN
	END
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Char_StatPoint_Dec]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_StatPoint_Dec]
/*
Character decrement statpoint
2005.11 By CJC
 input:
   See SQL
   
 output: 
   0 = error
   1 = update ok
   
*/
@nCharNo int,
@nStatPointType tinyint,
-- Output var
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- CHECK nRedistributePoint
/* DO NOT USE nRedistributePoint
DECLARE @nRedistributePoint tinyint
SET @nRedistributePoint = 0
SELECT @nRedistributePoint = nRedistributePoint FROM tCharacter WHERE nCharNo = @nCharNo
IF @nRedistributePoint < 1
BEGIN
	SET @nRet = 0
	RETURN
END
*/
-- CHECK Type and Decrement stat-point
DECLARE @nStatPoint tinyint
IF @nStatPointType = 0
BEGIN
	SELECT @nStatPoint = nStrength FROM tCharacter WHERE nCharNo = @nCharNo
	IF @nStatPoint < 1
	BEGIN
		SET @nRet = 0
		RETURN
	END
	
	UPDATE tCharacter	SET nStrength	= nStrength - 1					WHERE nCharNo = @nCharNo AND nStrength > 0
--	UPDATE tCharacter	SET nRedistributePoint = nRedistributePoint - 1 WHERE nCharNo = @nCharNo AND nRedistributePoint > 0
END
IF @nStatPointType = 1
BEGIN
	SELECT @nStatPoint = nConstitute FROM tCharacter WHERE nCharNo = @nCharNo
	IF @nStatPoint < 1
	BEGIN
		SET @nRet = 0
		RETURN
	END
	
	UPDATE tCharacter	SET nConstitute = nConstitute - 1				WHERE nCharNo = @nCharNo AND nConstitute > 0
--	UPDATE tCharacter	SET nRedistributePoint = nRedistributePoint - 1	WHERE nCharNo = @nCharNo AND nRedistributePoint > 0
END
	
IF @nStatPointType = 2
BEGIN
	SELECT @nStatPoint = nDexterity FROM tCharacter WHERE nCharNo = @nCharNo
	IF @nStatPoint < 1
	BEGIN
		SET @nRet = 0
		RETURN
	END
	
	UPDATE tCharacter	SET nDexterity = nDexterity - 1					WHERE nCharNo = @nCharNo AND nDexterity > 0
--	UPDATE tCharacter	SET nRedistributePoint = nRedistributePoint - 1	WHERE nCharNo = @nCharNo AND nRedistributePoint > 0
END
IF @nStatPointType = 3
BEGIN
	SELECT @nStatPoint = nIntelligence FROM tCharacter WHERE nCharNo = @nCharNo
	IF @nStatPoint < 1
	BEGIN
		SET @nRet = 0
		RETURN
	END
	
	UPDATE tCharacter	SET nIntelligence = nIntelligence - 1			WHERE nCharNo = @nCharNo AND nIntelligence > 0
--	UPDATE tCharacter	SET nRedistributePoint = nRedistributePoint - 1 WHERE nCharNo = @nCharNo AND nRedistributePoint > 0
END
IF @nStatPointType = 4 
BEGIN
	SELECT @nStatPoint = nMentalPower FROM tCharacter WHERE nCharNo = @nCharNo
	IF @nStatPoint < 1
	BEGIN
		SET @nRet = 0
		RETURN
	END
	
	UPDATE tCharacter	SET nMentalPower = nMentalPower - 1				WHERE nCharNo = @nCharNo AND nMentalPower > 0
--	UPDATE tCharacter	SET nRedistributePoint = nRedistributePoint - 1 WHERE nCharNo = @nCharNo AND nRedistributePoint > 0
END
-- Check Error
IF @@ERROR <> 0 OR @nStatPointType > 4
BEGIN
	SET @nRet = 0
	RETURN
END
SET @nRet = 1
-- end of file


GO
/****** Object:  StoredProcedure [dbo].[p_Char_StatPoint_Inc]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_StatPoint_Inc]
/*
Character increment statpoint
2005.11 By CJC
 input:
   See SQL
   
 output: 
   0 = error
   1 = update ok
   
*/
@nCharNo int,
@nStatPointType tinyint,
-- Output var
@nRet int OUTPUT
AS
SET NOCOUNT ON
IF @nStatPointType = 0 UPDATE tCharacter SET nStrength		= nStrength + 1		WHERE nCharNo = @nCharNo
IF @nStatPointType = 1 UPDATE tCharacter SET nConstitute	= nConstitute + 1	WHERE nCharNo = @nCharNo
IF @nStatPointType = 2 UPDATE tCharacter SET nDexterity		= nDexterity + 1	WHERE nCharNo = @nCharNo
IF @nStatPointType = 3 UPDATE tCharacter SET nIntelligence	= nIntelligence + 1 WHERE nCharNo = @nCharNo
IF @nStatPointType = 4 UPDATE tCharacter SET nMentalPower	= nMentalPower + 1	WHERE nCharNo = @nCharNo
-- check error
IF @@ERROR <> 0 OR @nStatPointType > 4
BEGIN
	SET @nRet = 0
	RETURN
END
SET @nRet = 1
-- end of file


GO
/****** Object:  StoredProcedure [dbo].[p_Char_SubExp]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-04-07
@return	0		<성공>
	others		<실패>
@brief	케릭서 저장 프로시져화.
==================================================*/
CREATE PROCEDURE [dbo].[p_Char_SubExp]
@nCharNo int,
@nExp bigint
AS
SET NOCOUNT ON
UPDATE tCharacter 
	SET 
		nExp=nExp-@nExp
	WHERE nCharNo=@nCharNo
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Wedding_Cancel_Propose]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Wedding_Cancel_Propose]
	@CharANo INT,
	@CharBNo INT,
	@nRet INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT @nRet = 0
-- to Character A
	BEGIN TRAN
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharANo AND nPartnerCharNo = @CharBNo)
	BEGIN
		UPDATE tMarriage
		SET
			nStatus = 0,
			nSubStatus = 0
		WHERE
			nCharNo = @CharANo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
-- to Character B
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharBNo AND nPartnerCharNo = @CharANo)
	BEGIN
		UPDATE tMarriage
		SET
			nStatus = 0,
			nSubStatus = 0
		WHERE
			nCharNo = @CharBNo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
	COMMIT TRAN
	GOTO END_
ERROR_:
	ROLLBACK TRAN
	SELECT @nRet = 1
END_:
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Wedding_Divorce_by_Agree]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Wedding_Divorce_by_Agree]
	@CharANo INT,
	@CharBNo INT,
	@nRet INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT @nRet = 0
-- to Character A : applicant
	BEGIN TRAN
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharANo AND nPartnerCharNo = @CharBNo)
	BEGIN
		UPDATE tMarriage
		SET
			nSubStatus = 1,
			dSubWhen = DATEADD(minute, 10, GETDATE())
		WHERE
			nCharNo = @CharANo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
-- to Character B
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharBNo AND nPartnerCharNo = @CharANo)
	BEGIN
		UPDATE tMarriage
		SET
			nSubStatus = 2,
			dSubWhen = DATEADD(minute, 10, GETDATE())
		WHERE
			nCharNo = @CharBNo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
	COMMIT TRAN
	GOTO END_
ERROR_:
	ROLLBACK TRAN
	SELECT @nRet = 1
END_:
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Wedding_Divorce_by_Force]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Wedding_Divorce_by_Force]
	@CharANo INT,
	@CharBNo INT,
	@nRet INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT @nRet = 0
-- to Character A : applicant
	BEGIN TRAN
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharANo AND nPartnerCharNo = @CharBNo)
	BEGIN
		UPDATE tMarriage
		SET
			nSubStatus = 3,
			dSubWhen = DATEADD(Day, 3, GETDATE())
--			dSubWhen = DATEADD(minute, 3, GETDATE())
		WHERE
			nCharNo = @CharANo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
-- to Character B
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharBNo AND nPartnerCharNo = @CharANo)
	BEGIN
		UPDATE tMarriage
		SET
			nSubStatus = 4,
			dSubWhen = DATEADD(Day, 3, GETDATE())
--			dSubWhen = DATEADD(minute, 3, GETDATE())
		WHERE
			nCharNo = @CharBNo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
	COMMIT TRAN
	GOTO END_
ERROR_:
	ROLLBACK TRAN
	SELECT @nRet = 1
END_:
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Wedding_Divorce_Cancel]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Wedding_Divorce_Cancel]
	@CharANo INT,
	@CharBNo INT,
	@IncreseCount TINYINT,
	@SubStatusA TINYINT OUTPUT,
	@SubStatusB TINYINT OUTPUT,
	@nRet INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT @nRet = 0
-- to Character A : applicant
	BEGIN TRAN
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharANo AND nPartnerCharNo = @CharBNo)
	BEGIN
		SELECT @SubStatusA = nSubStatus FROM tMarriage WHERE nCharNo = @CharANo
		UPDATE tMarriage
		SET
			nSubStatus = nSubStatus + 4,
			nDivorceCancel = nDivorceCancel + @IncreseCount,
			dSubWhen = GETDATE()
		WHERE
			nCharNo = @CharANo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
-- to Character B
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharBNo AND nPartnerCharNo = @CharANo)
	BEGIN
		SELECT @SubStatusB = nSubStatus FROM tMarriage WHERE nCharNo = @CharBNo
		UPDATE tMarriage
		SET
			nSubStatus = 0,
			dSubWhen = GETDATE()
		WHERE
			nCharNo = @CharBNo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
	COMMIT TRAN
	GOTO END_
ERROR_:
	ROLLBACK TRAN
	SELECT @nRet = 1
END_:
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Wedding_Divorce_Do]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Wedding_Divorce_Do]
	@CharANo INT,
	@CharBNo INT,
	@nRet INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT @nRet = 0
-- to Character A : applicant
	BEGIN TRAN
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharANo AND nPartnerCharNo = @CharBNo)
	BEGIN
		UPDATE tMarriage
		SET
			nStatus = 3,
			nSubStatus = 1,
			dSubWhen = DATEADD(minute, 3, GETDATE())
--			dSubWhen = DATEADD(day, 7, GETDATE())
		WHERE
			nCharNo = @CharANo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
-- to Character B
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharBNo AND nPartnerCharNo = @CharANo)
	BEGIN
		UPDATE tMarriage
		SET
			nStatus = 3,
			nSubStatus = 1,
			dSubWhen = DATEADD(minute, 3, GETDATE())
--			dSubWhen = DATEADD(day, 7, GETDATE())
		WHERE
			nCharNo = @CharBNo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
	COMMIT TRAN
	GOTO END_
ERROR_:
	ROLLBACK TRAN
	SELECT @nRet = 1
END_:
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Wedding_Divorce_Do_by_Item]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Wedding_Divorce_Do_by_Item]
	@CharANo INT,
	@CharBNo INT,
	@nRet INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT @nRet = 0
-- to Character A : applicant
	BEGIN TRAN
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharANo AND nPartnerCharNo = @CharBNo)
	BEGIN
		UPDATE tMarriage
		SET
			nStatus = 3,
			nSubStatus = 1,
			-- 즉시 결혼도 가능하달라고 해서 수정함
			dSubWhen = DATEADD(second, 5, GETDATE())
		WHERE
			nCharNo = @CharANo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
-- to Character B
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharBNo AND nPartnerCharNo = @CharANo)
	BEGIN
		UPDATE tMarriage
		SET
			nStatus = 3,
			nSubStatus = 2,
			-- 즉시 결혼도 가능하달라고 해서 수정함
			dSubWhen = DATEADD(second, 5, GETDATE())
		WHERE
			nCharNo = @CharBNo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
	COMMIT TRAN
	GOTO END_
ERROR_:
	ROLLBACK TRAN
	SELECT @nRet = 1
END_:
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Wedding_Do]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Wedding_Do] 
	@CharANo INT,
	@CharBNo INT,
	@nRet INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT @nRet = 0
-- to Character A
	BEGIN TRAN
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharANo AND nPartnerCharNo = @CharBNo)
	BEGIN
		UPDATE tMarriage
		SET
			nStatus = 2,
			nSubStatus = 0,
			dWhen = GETDATE(),
--			dSubWhen = DATEADD(day, 7, GETDATE()),
			dSubWhen = DATEADD(minute, 3, GETDATE()),
			nMarriageCount = nMarriageCount + 1,
			nDivorceCancel = 0
		WHERE
			nCharNo = @CharANo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
-- to Character B
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharBNo AND nPartnerCharNo = @CharANo)
	BEGIN
		UPDATE tMarriage
		SET
			nStatus = 2,
			nSubStatus = 0,
			dWhen = GETDATE(),
--			dSubWhen = DATEADD(day, 7, GETDATE()),
			dSubWhen = DATEADD(minute, 3, GETDATE()),
			nMarriageCount = nMarriageCount + 1,
			nDivorceCancel = 0
		WHERE
			nCharNo = @CharBNo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE GOTO ERROR_
	COMMIT TRAN
	GOTO END_
ERROR_:
	ROLLBACK TRAN
	SELECT @nRet = 1
END_:
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Wedding_Escape_Divorce_State]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Wedding_Escape_Divorce_State]
	@CharNo INT,
	@nRet INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharNo)
	BEGIN
		SELECT @nRet = 0
		UPDATE tMarriage
		SET
			nStatus = 0,
			nSubStatus = 0,
			nDivorceCancel = 0
		WHERE
			nCharNo = @CharNo
	END
	ELSE
	BEGIN
		SELECT @nRet = 1
	END
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Wedding_Get_Partner_Info]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Wedding_Get_Partner_Info]
	@CharNo INT
AS
BEGIN
	SET NOCOUNT ON
	SELECT nLevel, dLastLoginDate FROM tCharacter WHERE nCharNo = @CharNo
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Wedding_Propose]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Wedding_Propose]
	@CharANo INT,
	@CharBNo INT,
	@nRet INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT @nRet = 0
-- to Character A
	BEGIN TRAN
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharANo)
	BEGIN
		UPDATE tMarriage
		SET
			nPartnerCharNo = @CharBNo,
			nStatus = 1,
			nSubStatus = 0,
			dWhen = GETDATE(),
			dSubWhen = DATEADD(day, 3, GETDATE())
		WHERE
			nCharNo = @CharANo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE
	BEGIN
		INSERT tMarriage(nCharNo, nPartnerCharNo, nStatus, nSubStatus, dWhen, dSubWhen)
		VALUES(@CharANo, @CharBNo, 1,  0, GETDATE(), DATEADD(day, 3, GETDATE()))		
		 IF @@ERROR <> 0 GOTO ERROR_
	END
-- to Character B
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharBNo)
	BEGIN
		UPDATE tMarriage
		SET
			nPartnerCharNo = @CharANo,
			nStatus = 1,
			nSubStatus = 0,
			dWhen = GETDATE(),
			dSubWhen = DATEADD(day, 3, GETDATE())
		WHERE
			nCharNo = @CharBNo
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	ELSE
	BEGIN
		INSERT tMarriage(nCharNo, nPartnerCharNo, nStatus, nSubStatus, dWhen, dSubWhen)
		VALUES(@CharBNo, @CharANo, 1,  0, GETDATE(), DATEADD(day, 3, GETDATE()))		
		 IF @@ERROR <> 0 GOTO ERROR_
	END
	COMMIT TRAN
	GOTO END_
ERROR_:
	ROLLBACK TRAN
	SELECT @nRet = 1
END_:
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_WeddingStatus_Get]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_WeddingStatus_Get]
	@CharNo INT
AS
BEGIN
	SET NOCOUNT ON

	IF NOT EXISTS(SELECT * FROM tMarriage WHERE nCharNo = @CharNo)
	BEGIN
		SELECT @CharNo, 0, 0, GETDATE(), GETDATE(), 0, 0
	END
	ELSE
	BEGIN
		SELECT nPartnerCharNo, nStatus, nSubStatus, dWhen, dSubWhen, nMarriageCount, nDivorceCancel FROM tMarriage WHERE nCharNo = @CharNo
	END

	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_WeddingStatus_Set]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_WeddingStatus_Set]
	@CharNo INT,
	@PartnerCharNo INT,
	@Status SMALLINT,
	@SubStatus SMALLINT,
	@When DATETIME,
	@SubWhen DATETIME,
	@MarriageCount TINYINT,
	@DivorceCancel TINYINT
AS
BEGIN
	SET NOCOUNT ON
	IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @CharNo)
	BEGIN
		UPDATE tMarriage
		SET
			nPartnerCharNo = @PartnerCharNo,
			nStatus = @Status,
			nSubStatus = @SubStatus,
			dWhen = @When,
			dSubWhen = @SubWhen,
			nMarriageCount = @MarriageCount,
			nDivorceCancel = @DivorceCancel
		WHERE
			nCharNo = @CharNo
	END
	ELSE
	BEGIN
		INSERT tMarriage(nCharNo, nPartnerCharNo, nStatus, nSubStatus, dWhen, dSubWhen)
		VALUES(@CharNo, @PartnerCharNo, @Status, @SubStatus, @When, @SubWhen)
		
	END
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Char_Wipe]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Char_Wipe]
/*
Character Wipe(Erase)
2006.5 By CJC
 input:
	nCharNo
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
DELETE FROM tFriend WHERE nCharNo = @nCharNo			-- 관계에 의해 삭제됨
DELETE FROM tFriend WHERE nFriendCharNo = @nCharNo	-- 친구 테이블 순환 참고 없앰용
DELETE FROM tCharacter WHERE nCharNo = @nCharNo
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Event_Friend_Reward]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-05-22
@return	0		<성공>
	others		<실패>
@brief
==================================================*/
CREATE PROCEDURE [dbo].[p_Event_Friend_Reward]
@nEventUserNo	int,
@nFriendUserNo	int,
@nFriendCharNo	int,
@nItemKey	bigint,
@err 		smallint OUTPUT
AS
	SET NOCOUNT ON
	-------------------------------------------------------------------------
	-- 오늘은 형이쏜다 이벤트 보상용
	--
	-- 이벤트유저에게는					이벤트캐쉬 1000 지급
	-- 이벤트유저가 추천한 친구에게는	이벤트캐쉬  500 지급
	-------------------------------------------------------------------------
	BEGIN TRAN
	EXEC @err = Account.dbo.usp_Cash_setCash @nEventUserNo, 2,  1000, N'20070629_형이쏜다'
	IF @err < 0 BEGIN
		ROLLBACK TRAN
		RETURN
	END
	ELSE BEGIN
		EXEC @err = Account.dbo.usp_Cash_setCash @nFriendUserNo, 2,  500, N'20070629_형이쏜다'
		IF @err = 0 BEGIN
			COMMIT TRAN
			RETURN
		END
		ELSE BEGIN
			ROLLBACK TRAN
			RETURN
		END
	END
	SET NOCOUNT OFF
/*
-------------------------------------------------------------------------
-- 예전의 친구야 샤인하자 보상용 - 시작
--	이벤트 친구에게 보상한다.
--	개정창고 4 맨끝 위치부터 차곡차곡 쌓아간다.
--	개정창고 2 맨첨까지 다 쌓았을경우. 혹시 빈 슬롯을 찾는다(GOTO CRITICAL)
--	정말로 넣을자리가 없는경우 FULL 리턴값을 리턴한다.
-------------------------------------------------------------------------
DECLARE
@nLevel 			smallint,
@nRewardItemID		int,
@nLevelReward_1_23	int,
@nLevelReward_24_47	int,
@nLevelReward_48_100	int,
@nStorage_Min		smallint,
@nStorage_Max		smallint,
@nStorageType		tinyint,
@nItemID		int,
@nOptionType		smallint,
@nOptionData		bigint,
@nOldItemKey		bigint
-- Hard Fixed...
SET @nStorage_Max 		= 143 	--개정창고 4 맨끝 위치.
SET @nStorageType 		= 6 	--개정창고
SET @nLevelReward_1_23 		= 8004 	-- 축복의 릭스(강도1)
SET @nLevelReward_24_47 	= 8013 	-- 축복의 릭스(강도2)
SET @nLevelReward_48_100 	= 8022 	-- 축복의 릭스(강도3)
SET @nOptionType 		= 1	-- Max = 255
SELECT @nLevel = nLevel FROM tCharacter WITH(READUNCOMMITTED) 
	WHERE nCharNo = @nFriendCharNo
IF @@ROWCOUNT = 0
BEGIN
	SET @err = 1
	PRINT('Not Exitist Friend')
	RETURN @@ERROR
END
PRINT('@nLeve=')
PRINT(@nLevel)
IF @nLevel > 0 AND @nLevel < 24
	SET @nRewardItemID = @nLevelReward_1_23
ELSE IF @nLevel > 23 AND @nLevel < 48
	SET @nRewardItemID = @nLevelReward_24_47
ELSE
	SET @nRewardItemID = @nLevelReward_48_100
PRINT('@nRewardItemID=')
PRINT(@nRewardItemID)
SELECT @nStorage_Min = ISNULL(MIN( nStorage ), 0) FROM tItem WHERE nOwner=@nFriendUserNo AND nStorageType =@nStorageType 
	AND ( nItemID= @nLevelReward_1_23 OR nItemID= @nLevelReward_24_47 OR nItemID= @nLevelReward_48_100 )
PRINT('@nStorage_Min=')
PRINT(@nStorage_Min)
-- 개정창고 2 3 4 번 다 썼다.(@nStorage_Min=36)
IF @nStorage_Min > 0 AND @nStorage_Min < 37 
	BEGIN
		PRINT('IF @nStorage_Min > 0 AND @nStorage_Min < 36 ')
		GOTO CRITICAL
	END
IF @nStorage_Min = 0
	BEGIN
		SET	@nStorage_Min = @nStorage_Max
		SET	@nOptionData = 5
	END
ELSE
	BEGIN
		SELECT @nItemID = I.nItemID, @nOptionData=O.nOptionData, @nOldItemKey=I.nItemKey FROM tItem I
			INNER JOIN tItemOptions O ON I.nItemKey = O.nItemKey AND O.nOptionType = @nOptionType
			WHERE I.nOwner=@nFriendUserNo AND I.nStorageType =@nStorageType 
			AND I.nStorage = @nStorage_Min 
		PRINT('@@ROWCOUNT=')
		PRINT(@@ROWCOUNT)
		PRINT('@nItemID=')
		PRINT(@nItemID)
		PRINT('@nOptionData=')
		PRINT(@nOptionData)
		IF @nRewardItemID = @nItemID
			BEGIN
				-- 기존값에 추가한다.
				IF @nOptionData > 0 AND @nOptionData < 6 
				BEGIN
					SET	@nOptionData = @nOptionData+5
					--SET	@nStorage_Min = @nStorage_Min
				END
				ELSE
				BEGIN
					SET 	@nOptionData = 5
					SET	@nStorage_Min = @nStorage_Min-1
					PRINT('SET	@nStorage_Min = @nStorage_Min-1')
					PRINT(@nStorage_Min)
				END
			END
		ELSE
			BEGIN
				SET	@nStorage_Min = @nStorage_Min-1
				SET	@nOptionData = 5
			END
		
	END
-- 넣으려는 자리에 다른 아이템이 있는지 체크.(이벤트 전에 들어가 있던 아이템)
IF @nOptionData = 5
BEGIN
	IF EXISTS (SELECT nItemID  FROM tItem WHERE nOwner=@nFriendUserNo AND nStorageType =@nStorageType 
		AND nStorage=@nStorage_Min )
	BEGIN
		GOTO CRITICAL
	END
END
-- 아템 넣기.
BEGIN TRANSACTION
-- 새롭게 아템을 넣는다.
IF @nOptionData = 5
	BEGIN
		PRINT('INSERT tItem nItemKey')
		PRINT(@nItemKey)
		INSERT INTO tItem(nItemKey, nStorageType, nOwner, nStorage, nItemID, nFlags)
			VALUES(@nItemKey, @nStorageType, @nFriendUserNo, @nStorage_Min, @nRewardItemID, 0 )
		IF @@ERROR <> 0
		BEGIN
			GOTO ERR
		END
		PRINT('INSERT tItemOptions nItemKey')
		PRINT(@nItemKey)
		INSERT INTO tItemOptions(nItemKey, nOptionType, nOptionData)
			VALUES(@nItemKey, @nOptionType, @nOptionData )
		IF @@ERROR <> 0
		BEGIN
			GOTO ERR
		END
	END
-- 기존에 개수를 늘린다.
ELSE
	BEGIN
		PRINT('UPDATE tItemOptions nItemKey')
		PRINT(@nOldItemKey)
		UPDATE tItemOptions
		SET nOptionData=@nOptionData
		WHERE nItemKey = @nOldItemKey
		IF @@ERROR <> 0
		BEGIN
			GOTO ERR
		END
	END
COMMIT TRANSACTION
PRINT('COMMIT')
SET @err = 0
RETURN @@ERROR
ERR:
ROLLBACK TRANSACTION
PRINT('ROLLBACK')
SET @err = 2
RETURN @@ERROR
CRITICAL:
--  빈슬롯을 찾는다.
PRINT('CRITICAL')
declare
@nStrorageCurser int
SET @nStrorageCurser = @nStorage_Max
WHILE @nStrorageCurser > 35
BEGIN
	SELECT @nItemID = I.nItemID, @nOptionData=O.nOptionData, @nOldItemKey=I.nItemKey FROM tItem I
		INNER JOIN tItemOptions O ON I.nItemKey = O.nItemKey AND O.nOptionType = @nOptionType
		WHERE I.nOwner=@nFriendUserNo AND I.nStorageType =@nStorageType 
		AND I.nStorage =@nStrorageCurser
	IF @@ROWCOUNT = 0 
		BEGIN
			BREAK
		END
	ELSE
		BEGIN
			SET @nStrorageCurser = @nStrorageCurser-1
			CONTINUE
		END
END
IF @nStrorageCurser = 35
	BEGIN
		PRINT('FULL STORAGE')
		SET @err = 3
	END
ELSE
	BEGIN
		BEGIN TRANSACTION
		PRINT('@nStrorageCurser')
		PRINT(@nStrorageCurser)
		INSERT INTO tItem(nItemKey, nStorageType, nOwner, nStorage, nItemID, nFlags)
			VALUES(@nItemKey, @nStorageType, @nFriendUserNo, @nStrorageCurser, @nRewardItemID, 0 )
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRANSACTION
			PRINT('ROLLBACK')
			SET @err = 2
			RETURN @@ERROR
		END
		PRINT('INSERT 2 tItemOptions nItemKey')
		PRINT(@nItemKey)
		INSERT INTO tItemOptions(nItemKey, nOptionType, nOptionData)
			VALUES(@nItemKey, @nOptionType, @nOptionData )
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRANSACTION
			PRINT('ROLLBACK')
			SET @err = 2
			RETURN @@ERROR
		END
		COMMIT TRANSACTION
		SET @err = 0
	END
RETURN @@ERROR
*/ -- 예전의 친구야 샤인하자 보상용 - 끝


GO
/****** Object:  StoredProcedure [dbo].[p_Event_WorldCup_Init]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-05-29
@return	0		<성공>
	others		<실패>
@brief	월드컵이벤트 
==================================================*/
CREATE PROCEDURE [dbo].[p_Event_WorldCup_Init]
@nCharNo int,
@bNewJoiner tinyint OUTPUT
AS
SET NOCOUNT ON
DECLARE
@dRegisterDate	datetime,
@dEventStartDate	datetime,
@dEventEndDate	datetime
SET @dEventStartDate = '2006-05-30' --테스트
SET @dEventEndDate =  '2006-06-07' --6월 06일까지.
IF GETDATE() > @dEventEndDate
BEGIN
	SET	@bNewJoiner = 0
	RETURN @@error
END
SELECT @dRegisterDate=dCreateDate   
	FROM tCharacter
	WHERE nCharNo = @nCharNo --AND 
IF @@ROWCOUNT = 0
BEGIN
	SET	@bNewJoiner = 0
	RETURN @@error
END
IF @dRegisterDate > @dEventStartDate AND @dRegisterDate < @dEventEndDate
	BEGIN
		SET	@bNewJoiner = 1
	END
ELSE
	BEGIN
		SET	@bNewJoiner = 0
	END
RETURN @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Friend_Del]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Friend_Del]
/*
Friend Delete
2004.12 By CJC
 input:
	nCharNo, nFriendCharNo = To be delete info.
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nFriendCharNo int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- cross delete
DELETE FROM tFriend WHERE nCharNo = @nCharNo AND nFriendCharNo = @nFriendCharNo
SET @nRet = @@ERROR
DELETE FROM tFriend WHERE nCharNo = @nFriendCharNo AND nFriendCharNo = @nCharNo 
SET @nRet = @nRet + @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Friend_Del_All]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Friend_Del_All]
/*
Friend Delete
2007.12 By CJC
 input:
	nCharNo = To be delete info.
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- cross delete
DELETE FROM tFriend WHERE nCharNo = @nCharNo OR nFriendCharNo = @nCharNo
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Friend_Get]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Friend_Get]
/*
Char Get friend
2004.12 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int,
@nFriendNo int
AS
SET NOCOUNT ON
SELECT 
F.nFriendCharNo,
F.nFlags, 
C.sID,
S.nClass,
C.nLevel,
C.sLoginZone,
C.dLastLoginDate
FROM tFriend AS F
INNER JOIN tCharacterShape AS S ON S.nCharNo =  @nFriendNo
INNER JOIN tCharacter AS C ON C.nCharNo = @nFriendNo AND C.bDeleted = 0
WHERE F.nCharNo = @nCharNo AND F.nFriendCharNo = @nFriendNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Friend_GetAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Friend_GetAll]
/*
Char Get friend all
2004.12 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int
AS
SET NOCOUNT ON
SELECT F.nFriendCharNo, F.nFlags, C.sID
FROM tFriend AS F
INNER JOIN tCharacter AS C ON C.nCharNo =  F.nFriendCharNo AND C.bDeleted = 0
WHERE F.nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Friend_GetNumOfFriend]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Friend_GetNumOfFriend]
/*
Char Get friend all
2004.12 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int,
@nNumOfFriend int OUTPUT
AS
SET NOCOUNT ON
SET @nNumOfFriend = 0
SELECT @nNumOfFriend = COUNT(*) FROM tFriend AS F WITH(READUNCOMMITTED) 
INNER JOIN tCharacter AS C WITH(READUNCOMMITTED) ON C.nCharNo = F.nFriendCharNo AND C.bDeleted = 0
WHERE F.nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Friend_Set]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Friend_Set]
/*
Char Set friend
2004.12 By CJC
 input:
	see SQL
	
 output:
	@nRet	0 = OK, 
			1 = friend and me are same char
			2 = i'm over max friend count
			3 = friend is over max friend count
			547 = DB error, nCharNo or nFriendCharNo is not existed Character(Foreign Key checked)
			2627 = DB error, already friend marked
	        ? = Other DB error code
	        
*/
@nMAXFRIEND smallint,
@nCharNo int,
@nFriendCharNo int,
@nFlags tinyint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- check firend and me are same char.
IF @nCharNo = @nFriendCharNo
BEGIN
	SET @nRet = 1
	RETURN
END
-- check over max firend
DECLARE @nFriendCount int
EXEC p_Friend_GetNumOfFriend @nCharNo, @nFriendCount OUTPUT
IF @nFriendCount >= @nMAXFRIEND
BEGIN
	SET @nRet = 2
	RETURN
END
EXEC p_Friend_GetNumOfFriend @nFriendCharNo, @nFriendCount OUTPUT
IF @nFriendCount >= @nMAXFRIEND
BEGIN
	SET @nRet = 3
	RETURN
END
-- add friend
BEGIN TRAN
INSERT tFriend (  nCharNo,  nFriendCharNo,  nFlags )
VALUES         ( @nCharNo, @nFriendCharNo, @nFlags )
SET @nRet = @@ERROR
if( @nRet <> 0 )
BEGIN
	ROLLBACK TRAN
	RETURN
END
-- add friend cross
INSERT tFriend (  nCharNo,  nFriendCharNo,  nFlags )
VALUES         ( @nFriendCharNo, @nCharNo, @nFlags )
SET @nRet = @@ERROR
if( @nRet <> 0 )
BEGIN
	ROLLBACK TRAN
	RETURN
END
COMMIT TRAN
RETURN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Delete]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Delete]
/*
Char Delete Guild
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
DELETE FROM tGuild WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Get]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Get]
/*
Get Guild
2006.2 By CJC
*/
@nNo int
AS
SET NOCOUNT ON
SELECT 
	sName,
	sPassword,
	nMaxMembers,
	nMoney,
	nType,
	nGrade,
	nFame,
	nStoneLevel,
	nExp,
	dCreateDate,
	dWarRequestDate,
	dWarStartDate,
	dWarEndDate,
	nWarEnemy,
	nWarWinCount,
	nWarLoseCount,
	nWarDrawCount,
	
	nDismissStatus,
	dDismissDate,
	dNotifyDate,
	sNotifyCharID,
	sNotify,
	
	sIntro
	
FROM tGuild WHERE @nNo = nNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_GetAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_GetAll]
/*
Char Get All Guild
2006.2 By CJC
*/
AS
SET NOCOUNT ON
SELECT
	nNo,
	sName,
	sPassword,
	nMaxMembers,
	nMoney,
	nType,
	nGrade,
	nFame,
	nStoneLevel,
	nExp,
	dCreateDate,
	dWarRequestDate,
	dWarStartDate,
	dWarEndDate,
	nWarEnemy,
	nWarWinCount,
	nWarLoseCount,
	nWarDrawCount,
	nDismissStatus,
	dDismissDate,
	dNotifyDate,
	sNotifyCharID,
	sNotify,
	
	sIntro
	
FROM tGuild
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_GetCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_GetCount]
/*
Char Get Guild Count
2006.2 By CJC
*/
@nCount int output
AS
SET NOCOUNT ON
SELECT @nCount = COUNT(*) FROM tGuild
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_GetIntro]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_GetIntro]
/*
Get Guild Intro
2006.2 By CJC
*/
@nNo int
AS
SET NOCOUNT ON
SELECT sIntro FROM tGuild WHERE @nNo = nNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_GetList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_GetList]
/*
Char Get All Guild lIst
2006.3 By blacksky
*/
AS
SET NOCOUNT ON
SELECT
	nNo,
	sName
	
FROM tGuild
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_GetListDetail]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_GetListDetail]
/*
Char Get All Guild lIst detail
2007.11 By khris
*/
AS
SET NOCOUNT ON
SELECT
	nNo,
	sName,
	nMaxMembers,
	nType,
	nGrade,
	nFame,
	nExp
	
FROM tGuild
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_GetMyNo]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_GetMyNo]
/*
Get My Guild Number
2006.2 By CJC
Input:
	See SQL
	
Output:
	@nNo = 0, I'm not join guild
	@nNo = ?, My guild No.
*/
@nCharNo int,
@nNo     int output
AS
SET NOCOUNT ON
SET @nNo = 0
SELECT @nNo = nNo FROM tGuildMember WHERE nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_GetName]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_GetName]
/*
Get Guild Intro
2006.2 By Blacksky
*/
@nNo int
AS
SET NOCOUNT ON
SELECT sName FROM tGuild WHERE @nNo = nNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_GetNotify]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_GetNotify]
/*
Get Guild Notify
2006.2 By CJC
*/
@nNo int
AS
SET NOCOUNT ON
SELECT dNotifyDate, sNotifyCharID, sNotify FROM tGuild WHERE @nNo = nNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Grade_Growth]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Grade_Growth]
/*
Guild Grade Growth
2007.12.19 By Lunar
Input:
	See SQL
	
Output:
	nRet = 0,  OK.
	nRet = 1,  Error( Not exists GuildNo )
	nRet = 2,  Error( Not Guild Member or Not enough Member Grade(no master) )
	nRet = 3,  Error( Not enough upgrade money )
	nRet = 4,  Error( Not enough upgrade fame )
	nRet = 5,  Error( Failed update fame )
	nRet = 6,  Error( Failed update guild grade )
	nRet = 7,  Error( Failed update guild max member number )
*/
@nGuildNo		int,
@nCharNo		int,
@nGrade		tinyint,
@nMaxMembers	smallint,
@nMoney		bigint,
@nFame		int,
@nRemainFame		int	output,
@nRet			tinyint	output
AS
SET NOCOUNT ON
-- 에러코드 일단 세팅
SET @nRet = 0
-- 해당 길드가 없는지 확인
IF NOT EXISTS (SELECT nNo FROM tGuild WHERE nNo = @nGuildNo)
BEGIN
	SET @nRet = 1
	RETURN
END
/*
-- 필요아이템을 사용하는경우, 해당 아이템이 있는지 확인
IF @nMakerNeedItemID <> 65535
BEGIN
	IF NOT EXISTS (SELECT nItemID FROM tItem(NOLOCK) WHERE nOwner = @nMakerCharNo AND nItemID = @nMakerNeedItemID)
	BEGIN
		SET @nNo = -2
		RETURN
	END
END
*/
-- 해당 길드의 길드 맴버이며, 동시에 길드 마스터인지 확인.
IF NOT EXISTS (SELECT nCharNo FROM tGuildMember WHERE nCharNo = @nCharNo and nGrade = 0 )
BEGIN
	SET @nRet = 2
	RETURN
END
-- 길드 업그레이드 비용 적용
DECLARE @nRet2 tinyint
BEGIN TRAN
EXEC p_Char_MoneySub @nCharNo, @nMoney, @nRet2 OUTPUT
IF @nRet2 = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nRet = 3
	RETURN
END
-- 길드 명성치 확인
DECLARE @nFame2 int
SELECT @nFame2 = nFame FROM tGuild  WHERE nNo = @nGuildNo
IF @nFame2 < @nFame -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nRet = 4
	RETURN
END
-- 길드 업그레이드 명성치 비용 적용
SET @nRemainFame = @nFame2 - @nFame
EXEC p_Guild_SetFame @nGuildNo, @nRemainFame, @nRet2 OUTPUT
IF @nRet2 = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nRet = 5
	RETURN
END
-- 길드 업그레이드 적용(등급)
EXEC p_Guild_SetGrade @nGuildNo, @nGrade, @nRet2 OUTPUT
IF @nRet2 = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nRet = 6
	RETURN
END
-- 길드 업그레이드 적용(최대 인원)
EXEC p_Guild_SetMaxMembers @nGuildNo, @nMaxMembers, @nRet2 OUTPUT
IF @nRet2 = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nRet = 7
	RETURN
END
-- 만들기 성공
COMMIT TRAN
RETURN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Grade_Growth_NTC]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Grade_Growth_NTC]
/*
Guild Grade Growth
2007.12.19 By Lunar
Input:
	See SQL
	
Output:
	nRet = 0,  OK.
	nRet = 1,  Error( Not exists GuildNo )
	nRet = 2,  Error( Not Guild Member or Not enough Member Grade(no master) )
	nRet = 3,  Error( Not enough upgrade money )
	nRet = 4,  Error( Not enough upgrade fame )
	nRet = 5,  Error( Failed update fame )
	nRet = 6,  Error( Failed update guild grade )
	nRet = 7,  Error( Failed update guild max member number )
	nRet = 8,  Error( Failed update guild type )
*/
@nGuildNo		int,
@nCharNo		int,
@nGrade		tinyint,
@nType		tinyint,
@nMaxMembers	smallint,
@nMoney		bigint,
@nFame		int,
@nRemainFame		int	output,
@nRet			tinyint	output
AS
SET NOCOUNT ON
-- 에러코드 일단 세팅
SET @nRet = 0
-- 해당 길드가 없는지 확인
IF NOT EXISTS (SELECT nNo FROM tGuild WHERE nNo = @nGuildNo)
BEGIN
	SET @nRet = 1
	RETURN
END
/*
-- 필요아이템을 사용하는경우, 해당 아이템이 있는지 확인
IF @nMakerNeedItemID <> 65535
BEGIN
	IF NOT EXISTS (SELECT nItemID FROM tItem(NOLOCK) WHERE nOwner = @nMakerCharNo AND nItemID = @nMakerNeedItemID)
	BEGIN
		SET @nNo = -2
		RETURN
	END
END
*/
-- 해당 길드의 길드 맴버이며, 동시에 길드 마스터인지 확인.
IF NOT EXISTS (SELECT nCharNo FROM tGuildMember WHERE nCharNo = @nCharNo and nGrade = 0 )
BEGIN
	SET @nRet = 2
	RETURN
END
-- 길드 업그레이드 비용 적용
DECLARE @nRet2 tinyint
BEGIN TRAN
EXEC p_Char_MoneySub @nCharNo, @nMoney, @nRet2 OUTPUT
IF @nRet2 = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nRet = 3
	RETURN
END
-- 길드 명성치 확인
DECLARE @nFame2 int
SELECT @nFame2 = nFame FROM tGuild  WHERE nNo = @nGuildNo
IF @nFame2 < @nFame -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nRet = 4
	RETURN
END
-- 길드 업그레이드 명성치 비용 적용
SET @nRemainFame = @nFame2 - @nFame
EXEC p_Guild_SetFame @nGuildNo, @nRemainFame, @nRet2 OUTPUT
IF @nRet2 = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nRet = 5
	RETURN
END
-- 길드 업그레이드 적용(등급)
EXEC p_Guild_SetGrade @nGuildNo, @nGrade, @nRet2 OUTPUT
IF @nRet2 = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nRet = 6
	RETURN
END
-- 길드 업그레이드 적용(최대 인원)
EXEC p_Guild_SetMaxMembers @nGuildNo, @nMaxMembers, @nRet2 OUTPUT
IF @nRet2 = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nRet = 7
	RETURN
END
-- 길드 업그레이드 적용(길드 타입)
EXEC p_Guild_SetType @nGuildNo, @nType, @nRet2 OUTPUT
IF @nRet2 = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nRet = 8
	RETURN
END
-- 만들기 성공
COMMIT TRAN
RETURN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Make]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Make]
/*
Make Guild
2006.2 By CJC
Input:
	See SQL
	
Output:
	nNo = 0,   Error
	nNo = -1,  Error( Same guild name exist )
	nNo = -2,  Error( Not exists need item )
	nNo = -3,  Error( Other guild member )
	nNo = -4,  Error( Not enough maker money )
	nNo = -5,  Error( Make Guild error )
	nNo = -6,  Error( Maker to Join Guild master )
	nNo = 1~?, OK( Maked guild No )
*/
@sName nvarchar(18),
@sPassword nvarchar(9),
@nMaxMembers smallint,
@nType tinyint,
@nMakerCharNo int,
@nMakerPay bigint,
@nMakerNeedItemID int,
@nNo int output
AS
SET NOCOUNT ON
-- 에러코드 일단 세팅
SET @nNo = 0
-- 해당 길드가 있는지 확인
IF EXISTS (SELECT sName FROM tGuild(NOLOCK) WHERE sName = @sName)
BEGIN
	SET @nNo = -1
	RETURN
END
-- 필요아이템을 사용하는경우, 해당 아이템이 있는지 확인
IF @nMakerNeedItemID <> 65535
BEGIN
	IF NOT EXISTS (SELECT nItemID FROM tItem(NOLOCK) WHERE nOwner = @nMakerCharNo AND nItemID = @nMakerNeedItemID)
	BEGIN
		SET @nNo = -2
		RETURN
	END
END
-- 이미 다른 길드 가입했는지 확인
IF EXISTS (SELECT nCharNo FROM tGuildMember(NOLOCK) WHERE nCharNo = @nMakerCharNo)
BEGIN
	SET @nNo = -3
	RETURN
END
-- 길드 창설비용 적용
DECLARE @nRet tinyint
BEGIN TRAN
EXEC p_Char_MoneySub @nMakerCharNo, @nMakerPay, @nRet OUTPUT
IF @nRet = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nNo = -4
	RETURN
END
-- 길드 만들기
INSERT tGuild (  sName,  sPassword,  nMaxMembers,  nType )
VALUES        ( @sName, @sPassword, @nMaxMembers, @nType )
SET @nNo = @@IDENTITY
-- 길드 만들기 오류 확인
IF @@ERROR <> 0 
BEGIN
	ROLLBACK TRAN
	SET @nNo = -5
	RETURN
END
-- 만든 캐릭을 길마으로 추가
EXEC p_Guild_Member_Join @nNo, @nMakerCharNo, 0, @nRet OUTPUT
IF @nRet = 0
BEGIN 
	ROLLBACK TRAN
	SET @nNo = -6
	RETURN
END
-- 만들기 성공
COMMIT TRAN
RETURN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Make2]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [dbo].[p_Guild_Make2]
/*
Make Guild
2006.12.15 By CJC
Input:
	See SQL
	
Output:
	nNo = 0,   Error, Remain char money
	nNo = -1,  Error( Same guild name exist )
	nNo = -2,  Error( Not exists need item )
	nNo = -3,  Error( Other guild member )
	nNo = -4,  Error( Not enough maker money )
	nNo = -5,  Error( Make Guild error )
	nNo = -6,  Error( Maker to Join Guild master )
	nNo = 1~?, OK( Maked guild No )
*/
@sName nvarchar(18),
@sPassword nvarchar(9),
@nMaxMembers smallint,
@nType tinyint,
@nMakerCharNo int,
@nMakerPay bigint,
@nMakerNeedItemID int,
@nNo int output,
@nRemainCharMoney bigint output
AS
SET NOCOUNT ON
-- 에러코드 일단 세팅
SET @nNo = 0
-- 해당 길드가 있는지 확인
IF EXISTS (SELECT sName FROM tGuild(NOLOCK) WHERE sName = @sName)
BEGIN
	SET @nNo = -1
	RETURN
END
-- 필요아이템을 사용하는경우, 해당 아이템이 있는지 확인
IF @nMakerNeedItemID <> 65535
BEGIN
	IF NOT EXISTS (SELECT nItemID FROM tItem(NOLOCK) WHERE nOwner = @nMakerCharNo AND nItemID = @nMakerNeedItemID)
	BEGIN
		SET @nNo = -2
		RETURN
	END
END
-- 이미 다른 길드 가입했는지 확인
IF EXISTS (SELECT nCharNo FROM tGuildMember(NOLOCK) WHERE nCharNo = @nMakerCharNo)
BEGIN
	SET @nNo = -3
	RETURN
END
-- 길드 창설비용 적용
DECLARE @nRet tinyint
BEGIN TRAN
EXEC p_Char_MoneySub @nMakerCharNo, @nMakerPay, @nRet OUTPUT
IF @nRet = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nNo = -4
	RETURN
END
-- 길드 창설비용을 쓰고 남은돈 얻기
EXEC p_Char_MoneyGet @nMakerCharNo, @nRemainCharMoney OUTPUT, @nRet OUTPUT
IF @nRet = 0 -- 에러 확인
BEGIN
	ROLLBACK TRAN
	SET @nNo = -4
	RETURN
END
-- 길드 만들기
INSERT tGuild (  sName,  sPassword,  nMaxMembers,  nType )
VALUES        ( @sName, @sPassword, @nMaxMembers, @nType )
SET @nNo = @@IDENTITY
-- 길드 만들기 오류 확인
IF @@ERROR <> 0 
BEGIN
	ROLLBACK TRAN
	SET @nNo = -5
	RETURN
END
-- 만든 캐릭을 길마으로 추가
EXEC p_Guild_Member_Join @nNo, @nMakerCharNo, 0, @nRet OUTPUT
IF @nRet = 0
BEGIN 
	ROLLBACK TRAN
	SET @nNo = -6
	RETURN
END
-- 길드아카데미 생성
EXEC usp_GuildAcademy_setAcademy @nNo, @nMakerCharNo, 50, @nRet OUTPUT
IF @nRet <> 0 -- 길드아카데미 생성에서는 정상처리시 0을 return value로 가짐
BEGIN 
	ROLLBACK TRAN
	SET @nNo = @nRet
	RETURN
END
-- 만들기 성공
COMMIT TRAN
RETURN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Member_Get]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Member_Get]
/*
Get Guild Member
2006.2 By CJC
Input:
	See SQL
	
Output:
	fetch to take data
*/
@nNo int,
@nCharNo int
AS
SET NOCOUNT ON
SELECT G.dJoinDate, G.nGrade, G.nFlags, G.nExpRatio, G.sIntro, C.sID, S.nClass, C.nLevel, C.sLoginZone, C.dLastLoginDate
FROM tGuildMember    AS G INNER JOIN 
     tCharacter      AS C ON C.nCharNo =  G.nCharNo AND C.bDeleted = 0 INNER JOIN 
     tCharacterShape AS S ON S.nCharNo =  G.nCharNo
WHERE G.nCharNo = @nCharNo AND G.nNo = @nNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Member_GetAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Member_GetAll]
/*
Get Guild Member All
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int
AS
SET NOCOUNT ON
SELECT G.nCharNo, G.dJoinDate, G.nGrade, G.nFlags, G.nExpRatio, G.sIntro, C.sID, S.nClass, C.nLevel, C.sLoginZone, C.dLastLoginDate
FROM tGuildMember    AS G INNER JOIN 
     tCharacter      AS C ON C.nCharNo =  G.nCharNo AND C.bDeleted = 0 INNER JOIN 
     tCharacterShape AS S ON S.nCharNo =  G.nCharNo
WHERE G.nNo = @nNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Member_GetCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Member_GetCount]
/*
Get Guild Member Count
2006.2 By CJC
Input:
	See SQL
	
Output:
	nCount = Number of member
*/
@nNo int,
@nCount int output
AS
SET NOCOUNT ON
SELECT @nCount = COUNT(*) FROM tGuildMember AS G WITH(READUNCOMMITTED) 
INNER JOIN tCharacter AS C WITH(READUNCOMMITTED) ON C.nCharNo = G.nCharNo AND C.bDeleted = 0
WHERE G.nNo = @nNo 
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Member_Join]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Member_Join]
/*
Get Guild Member Join
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0, Error
	nRet = 1, OK
*/
@nNo int,
@nCharNo int,
@nGrade tinyint,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
-- 만들기
INSERT tGuildMember (  nNo,  nCharNo,  nGrade )
VALUES              ( @nNo, @nCharNo, @nGrade )
-- 오류 확인
IF @@ERROR <> 0 
BEGIN
	RETURN
END
SET @nRet = 1
-- end
RETURN


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Member_Leave]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Member_Leave]
/*
Get Guild Member Leave
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0, Error
	nRet = 1, OK
*/
@nNo int,
@nCharNo int,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
-- 삭제
DELETE FROM tGuildMember WHERE nNo = @nNo AND nCharNo = @nCharNo
SET @nRet = @@ROWCOUNT
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Member_SetExpRatio]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Member_SetExpRatio]
/*
Set Guild Member Exp Ratio
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error
	nRet = 1,  OK
*/
@nNo int,
@nCharNo int,
@nExpRatio smallint,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuildMember SET nExpRatio = @nExpRatio WHERE nNo = @nNo AND nCharNo = @nCharNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Member_SetFlags]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Member_SetFlags]
/*
Set Guild Member Flags
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error
	nRet = 1,  OK
*/
@nNo int,
@nCharNo int,
@nFlags int,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuildMember SET nFlags = @nFlags WHERE nNo = @nNo AND nCharNo = @nCharNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Member_SetGrade]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Set Guild Member Grade
2006.2 By CJC
Input:
	See SQL
2010.8.27. by kodong
	캐릭터명 변경 서비스를 통해 인간관계 초기화 아이템을 사용한 캐릭터에게는
	길드마스터 변경이 불가능하게 함.
	
	주의 : 반드시 캐릭터명 변경 서비스(인간관계 초기화) 시스템 이후 변경되어야 함.
2011.5.4 by kodong
	길드마스터가 두명이상 복수로 생기는 문제 수정
2011.9.30 by kodong
	길드마스터 이양 쿨타임 적용
Output:
	nRet = 0,  Error
	nRet = 1,  OK
*/
CREATE PROCEDURE [dbo].[p_Guild_Member_SetGrade]
	@nNo     int
,	@nCharNo int
,	@nGrade  tinyint
,	@nRet    int = 0 output
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @cnt int, @guildMaster int
	DECLARE @lastChangeDate datetime

	SET @nRet = 0
	SET @guildMaster = 0

	IF ISNULL(@nNo, 0) = 0 BEGIN
		SET @nRet = -1311
		RETURN
	END
	IF ISNULL(@nCharNo, 0) = 0 BEGIN
		SET @nRet = -1313
		RETURN
	END
	
	-- 캐릭터명 변경 서비스(인간관계 초기화) 아이템 추가로 인한 수정 by kodong
	SELECT @cnt = ISNULL(COUNT(nCharNo), 0) 
	  FROM tCharacterChangeID 
	 WHERE nCharNo = @nCharNo 
	   AND bFlag = 0 -- 반영 안된 기록이 있는 경우
	   AND bInit = 1 -- 인간관계 초기화를 설정한 경우
	IF @nGrade = 0 AND @cnt = 1 BEGIN
		SET @nRet = -1323
		RETURN
	END
	ELSE BEGIN
		BEGIN TRAN
		
		-- 길드마스터 변경 요청시 기존 길드마스터 캐릭터번호를 가져옴
		IF @nGrade = 0 BEGIN
			SELECT @guildMaster = ISNULL(MAX(nCharNo), 0) FROM tGuildMember WHERE nNo = @nNo AND nGrade = 0
			
			-- 길드마스터 이양 쿨타임 체크 by kodong 2011.9.30
			SELECT @lastChangeDate = MAX(dDate) FROM tLog_GuildMasterChange WITH(HOLDLOCK) WHERE nGuildNo = @nNo
			IF @lastChangeDate IS NOT NULL AND DATEADD(Day, 7, @lastChangeDate) > GETDATE() BEGIN
				ROLLBACK TRAN
				SET @nRet = -1324
				RETURN
			END
		END	
		
		-- 길드마스터 변경 요청과 기존 길드마스터 캐릭터번호가 존재하면 기존 길드마스터 모두를 일반 길드원으로 변경		
		IF @nGrade = 0 AND @guildMaster <> 0 BEGIN
			UPDATE tGuildMember SET nGrade = 6 WHERE nNo = @nNo AND nGrade = 0
			IF @@ERROR <> 0 BEGIN
				ROLLBACK TRAN
				SET @nRet = -1325
				RETURN
			END
		END		
		
		-- 길드원 권한 변경	
		UPDATE tGuildMember SET nGrade = @nGrade WHERE nNo = @nNo AND nCharNo = @nCharNo
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			ROLLBACK TRAN
			SET @nRet = -1325
		END
		ELSE BEGIN
			-- 길드마스터 이양 쿨타임 체크 by kodong 2011.9.30				
			IF @nGrade = 0 BEGIN
				INSERT INTO tLog_GuildMasterChange (nGuildNo, nOldGuildMaster, nNewGuildMaster)
				VALUES (@nNo, @guildMaster, @nCharNo)
			END
			
			COMMIT TRAN
			SET @nRet = 0
		END
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Member_SetIntro]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Member_SetIntro]
/*
Set Guild Member Intro
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error
	nRet = 1,  OK
*/
@nNo int,
@nCharNo int,
@sIntro nvarchar(64),
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuildMember SET sIntro = @sIntro WHERE nNo = @nNo AND nCharNo = @nCharNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_MoneyAdd]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_MoneyAdd]
/*
Add Guild Money
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild/member, not enough member's money)
	nRet = 1,  OK
*/
@nNo int,
@nMemberCharNo int,
@nMoneyAdd bigint,
@nMemberMoney bigint output,
@nTotalMoney bigint output,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
-- 길원의 금액을 얻는다
EXEC p_Char_MoneyGet @nMemberCharNo, @nMemberMoney OUTPUT, @nRet OUTPUT
IF @nRet <> 1 
	RETURN
-- 길원의 보유 금액이 요청한 금액보다 적으면 실패처리 한다.
IF @nMoneyAdd > @nMemberMoney
	RETURN
-- 길드 금액처리
BEGIN TRAN
-- 1. 길원 금액 빼기
EXEC p_Char_MoneySub @nMemberCharNo, @nMoneyAdd, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 0
	RETURN
END
-- 2. 길원의 남은 금액 얻기
EXEC p_Char_MoneyGet @nMemberCharNo, @nMemberMoney OUTPUT, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 0
	RETURN
END
-- 3. 길드 금액 증가
UPDATE tGuild SET nMoney = nMoney + @nMoneyAdd WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 0
	RETURN
END
-- 4. 길드 최종급액 얻기
SELECT @nTotalMoney = nMoney FROM tGuild WHERE nNo = @nNo
IF @@ROWCOUNT <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 0
	RETURN
END
-- 완료
SET @nRet = 1
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_MoneySub]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_MoneySub]
/*
Sub Guild Money
2007.11 By Lunar
Input:
	See SQL
	
Output:
	nRet =   0, OK
		1, Fail get Guild Money
		2, Guild Money Sub Failed(Not enough money)
		3, Guild Money Update Failed
		4, Member Money Update Failed
		5, Fail get Member Money
		6, Fail get Final Guild Money
*/
@nNo int,
@nMemberCharNo int,
@nMoneySub bigint,
@nMemberMoney bigint output,
@nTotalMoney bigint output,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
SET @nMemberMoney = 0
SET @nTotalMoney = 0
-- 길드의 금액을 얻는다
SELECT @nTotalMoney = nMoney FROM tGuild WHERE nNo = @nNo
IF @@ERROR <> 0
BEGIN
	SET @nRet = 1
	RETURN
END
-- 길드의 보유 금액이 요청한 금액보다 적으면 실패처리 한다.
IF @nMoneySub > @nTotalMoney
BEGIN
	SET @nRet = 2
	RETURN
END
-- 길드 금액처리
BEGIN TRAN
-- 1. 길드 금액 빼기
UPDATE tGuild SET nMoney = nMoney - @nMoneySub WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 3
	RETURN
END
-- 2. 길원 금액 증가
EXEC p_Char_MoneyAdd @nMemberCharNo, @nMoneySub, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 4
	RETURN
END
-- 3. 길원 금액 얻기
EXEC p_Char_MoneyGet @nMemberCharNo, @nMemberMoney OUTPUT, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 5
	RETURN
END
-- 4. 길드 최종급액 얻기
SELECT @nTotalMoney = nMoney FROM tGuild WHERE nNo = @nNo
IF @@ROWCOUNT <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 6
	RETURN
END
-- 완료
SET @nRet = 0
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_Set]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_Set]
/*
Update Guild Data
2006.3 By blacksky
*/
@nNo				int,
@sName				nvarchar(18),
@sPassword			nvarchar(9),
@nMaxMembers		smallint,
@nMoney				bigint,
@nType				tinyint,
@nGrade				tinyint,	
@nFame				int,
@nStoneLevel		smallint,
@nExp				bigint,
@dCreateDate		datetime,
@dWarRequestDate	datetime,
@dWarStartDate		datetime,
@dWarEndDate		datetime,
@nWarEnemy			int,
@nWarWinCount		int,
@nWarLoseCount		int,
@nWarDrawCount		int,
@nDismissStatus		tinyint,
@dDismissDate		datetime,
@dNotifyDate		datetime,
@sNotifyCharID		nvarchar(16),
@sNotify			nvarchar(512),
@sIntro				nvarchar(128),
@nRet				tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE
	tGuild
SET
	sName			= @sName,
	sPassword		= @sPassword,
	nMaxMembers		= @nMaxMembers,
	nMoney			= @nMoney,
	nType			= @nType,
	nGrade			= @nGrade,
	nFame			= @nFame,
	nStoneLevel		= @nStoneLevel,
	nExp			= @nExp,
	dCreateDate		= @dCreateDate,
	dWarRequestDate	= @dWarRequestDate,
	dWarStartDate	= @dWarStartDate,
	dWarEndDate		= @dWarEndDate,
	nWarEnemy		= @nWarEnemy,
	nWarWinCount	= @nWarWinCount,
	nWarLoseCount	= @nWarLoseCount,
	nWarDrawCount	= @nWarDrawCount,
	
	nDismissStatus	= @nDismissStatus,
	dDismissDate	= @dDismissDate,
	dNotifyDate		= @dNotifyDate,
	sNotifyCharID	= @sNotifyCharID,
	sNotify			= @sNotify,
	
	sIntro			= @sIntro
	
WHERE
	@nNo = nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetDismiss]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_SetDismiss]
/*
Set Guild Type
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@nDismissStatus tinyint,
@dDismissDate datetime,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuild SET nDismissStatus = @nDismissStatus, dDismissDate = @dDismissDate WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetExp]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_SetExp]
/*
Set Guild Exp
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@nExp bigint,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuild SET nExp = @nExp WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetFame]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_SetFame]
/*
Set Guild Fame
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@nFame int,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuild SET nFame = @nFame WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetGrade]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Set Guild Grade
2006.2 By CJC
Input:
	See SQL
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
CREATE PROCEDURE [dbo].[p_Guild_SetGrade]
	@nNo    int
,	@nGrade tinyint
,	@nRet   tinyint output
AS
BEGIN
	SET NOCOUNT ON

	SET @nRet = 0

	UPDATE tGuild SET nGrade = @nGrade WHERE nNo = @nNo
	SET @nRet = @@ROWCOUNT
	IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
	BEGIN
		SET @nRet = 0
		RETURN
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetIntro]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_SetIntro]
/*
Set Guild Intro
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@sIntro nvarchar(128),
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuild SET sIntro = @sIntro WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetMaxMembers]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_SetMaxMembers]
/*
Set Guild Grade
2007.12.19 By Lunar
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@nMaxMembers tinyint,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuild SET nMaxMembers = @nMaxMembers WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetMoney]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_SetMoney]
/*
Set Guild Exp
2007.11 By Lunar
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@nMoney bigint,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuild SET nMoney = @nMoney WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_setName]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : p_Guild_setName
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2008.9.24.
' Description :
'   길드명을 변경한다.
'	2008.9월 유료아이템 기획중 길드명을 변경하는 아이템이 추가됨에 따라 저장프로시저를
'	추가하게 되었음
' Parameter :
'	input Parameter
'		@nNo 	        : 길드번호
'		@sName          : 길드명
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-1311 : 길드번호가 입력되지 않았습니다.
'				-1312 : 길드명이 입력되지 않았습니다.
'				-1321 : 입력받은 길드번호의 길드가 존재하지 않습니다.
'				-1322 : 입력받은 길드명이 중복되는 길드명입니다.
'				-1393 : db error(update)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[p_Guild_setName]
	@nNo   int
,	@sName nvarchar(18)
,	@nRet  int = 0 output
AS
BEGIN
	SET NOCOUNT ON

	IF @nNo <= 0 BEGIN
		SET @nRet = -1311
		RETURN
	END

	IF LEN(ISNULL(@sName, '')) = 0 BEGIN
		SET @nRet = -1312
		RETURN
	END

	IF EXISTS(SELECT nNo FROM tGuild WHERE nNo = @nNo) BEGIN
		IF EXISTS(SELECT sName FROM tGuild WHERE sName = @sName) BEGIN
			SET @nRet = -1322
		END
		ELSE BEGIN

			BEGIN TRAN

			UPDATE tGuild SET sName = @sName WHERE nNo = @nNo
			IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
				ROLLBACK TRAN
				SET @nRet = -1393
			END
			ELSE BEGIN
				COMMIT TRAN
				SET @nRet = 0
			END
		END
	END
	ELSE BEGIN
		SET @nRet = -1321
	END

	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetNotify]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_SetNotify]
/*
Set Guild Notify
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@sNotifyCharID nvarchar(16),
@sNotify nvarchar(512),
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuild SET dNotifyDate = getdate(), sNotifyCharID = @sNotifyCharID, sNotify = @sNotify WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetStoneLevel]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_SetStoneLevel]
/*
Set Guild StoneLevel
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@nStoneLevel smallint,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuild SET nStoneLevel = @nStoneLevel WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetType]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_SetType]
/*
Set Guild Type
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@nType tinyint,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuild SET nType = @nType WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetWar]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_SetWar]
/*
Set Guild War
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@dWarRequestDate datetime,
@dWarStartDate datetime,
@dWarEndDate datetime,
@nWarEnemy int,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuild SET 
	dWarRequestDate = @dWarRequestDate,
	dWarStartDate = @dWarStartDate,
	dWarEndDate = @dWarEndDate,
	nWarEnemy = @nWarEnemy
WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Guild_SetWarResult]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Guild_SetWarResult]
/*
Set Guild War Result
2006.2 By CJC
Input:
	See SQL
	
Output:
	nRet = 0,  Error(Not found guild)
	nRet = 1,  OK
*/
@nNo int,
@nWarWinCount int,
@nWarLoseCount int,
@nWarDrawCount int,
@nRet tinyint output
AS
SET NOCOUNT ON
SET @nRet = 0
UPDATE tGuild SET 
	nWarWinCount = @nWarWinCount,
	nWarLoseCount = @nWarLoseCount,
	nWarDrawCount = @nWarDrawCount
WHERE nNo = @nNo
SET @nRet = @@ROWCOUNT
IF @@ERROR <> 0 OR @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 0
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_GuildTournament_Get]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_GuildTournament_Get]
/*
Get Tournament Guild Data
2007.5 By CJC
*/
@nGTNo int
AS
SET NOCOUNT ON
SELECT nType, nData FROM tGuildTournament WHERE @nGTNo = nGTNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_GuildTournament_GetAllTournamentList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_GuildTournament_GetAllTournamentList]
AS
BEGIN
	SELECT nGTNo
	FROM   tGuildTournament
	GROUP BY nGTNo
END


GO
/****** Object:  StoredProcedure [dbo].[p_GuildTournament_GetLastMatch]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_GuildTournament_GetLastMatch]
AS
BEGIN
	SELECT   nGTNo, nType, nData
	FROM      tGuildTournament
	WHERE   (nGTNo IN
                    (SELECT   MAX(nGTNo)
                     FROM      tGuildTournament))
             ORDER BY nType
END


GO
/****** Object:  StoredProcedure [dbo].[p_GuildTournament_Set]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_GuildTournament_Set]
/*
Set/Update Guild Tournament Data
2007.5 By CJC
*/
@nGTNo				int,
@nType				smallint,
@nData				int,
@nRet				int OUTPUT
AS
SET NOCOUNT ON
UPDATE tGuildTournament SET	nData = @nData WHERE nGTNo = @nGTNo AND nType = @nType
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tGuildTournament (  nGTNo,  nType,  nData )
	VALUES					( @nGTNo, @nType, @nData )
END
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_GuildTournament_Sync_with_world]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_GuildTournament_Sync_with_world]
	@BaseNumber INT,
	@LastMatchNumber INT OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @BackupIndex INT
	IF (SELECT COUNT(*) FROM tGuildTournament_backup) < 1
		SET @BackupIndex = 0
	ELSE
		BEGIN
			SELECT @BackupIndex = MAX(nIndex) + 1 FROM tGuildTournament_backup
		END
	INSERT INTO tGuildTournament_backup(nIndex, nGTNo, nType, nData) SELECT @BackupIndex, nGTNo, nType, nData FROM tGuildTournament WHERE nGTNo > @BaseNumber
	DELETE FROM tGuildTournament WHERE nGTNo > @BaseNumber
	SELECT @LastMatchNumber = MAX(nGTNo) FROM tGuildTournament
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_HolyPromise_CheckRing]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_HolyPromise_CheckRing]
/*
Holy promise check ring
2008.4 By CJC
 input:
	see SQL
	
 output:
	@nRet
	0 = No ring 
	1 = Yes ring
	-1 = DB error
*/
@nCharNo int,		-- 현재 캐릭
@nUpCharNo int,	-- 상위로 등록될 캐릭
@nRet int OUTPUT	-- 아미 상위로 등록되어 링구조가 되는지 결과확인값 리턴
AS
BEGIN
	SET NOCOUNT ON
	-- check are same char.
	IF @nCharNo = @nUpCharNo
	BEGIN
		SET @nRet = 1
		RETURN
	END
	DECLARE @nTempCharNo int
	DECLARE @nTempUpCharNo int
	SET @nTempCharNo = @nCharNo
	LOOP_UP:
	SET @nTempUpCharNo = 0
	SELECT @nTempUpCharNo = P.nUpCharNo FROM tHolyPromise AS P 
	INNER JOIN tCharacter AS C ON C.nCharNo =  P.nCharNo AND C.bDeleted = 0
	WHERE P.nCharNo = @nTempCharNo
	IF @nTempUpCharNo > 0
	BEGIN
		-- 링구조가 형성되는지 검사
		IF @nUpCharNo = @nTempUpCharNo
		BEGIN
			SET @nRet = 1
			RETURN
		END
		-- 다음 상위로 이동
		SET @nTempCharNo = @nTempUpCharNo
		GOTO LOOP_UP
	END
	-- 링구조 없음.
	SET @nRet = 0
	RETURN
END


GO
/****** Object:  StoredProcedure [dbo].[p_HolyPromise_Del]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_HolyPromise_Del]
/*
Delete holy promise
2008.4 By CJC
 input:
	see SQL
	
 output:
	@nRet
	0 = OK, 
	? = Other DB error code
	        
*/
@nCharNo int,
@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	-- Update/Inset data
	IF EXISTS( SELECT nCharNo FROM  tHolyPromise WHERE nCharNo=@nCharNo)
	BEGIN
		UPDATE tHolyPromise SET nUpCharNo=0, nFlags=0, dRegDate=GetDate() WHERE nCharNo=@nCharNo
		SET @nRet = @@ERROR
	END
	ELSE
		SET @nRet = 0
	RETURN
END


GO
/****** Object:  StoredProcedure [dbo].[p_HolyPromise_DelChar]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_HolyPromise_DelChar]
/*
Delete char holy promise
2008.4 By CJC
 input:
	see SQL
	
 output:
	@nRet
	0 = OK, 
	? = Other DB error code
	        
*/
@nDelCharNo int,
@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	DELETE FROM tHolyPromise WHERE nUpCharNo = @nDelCharNo
	SET @nRet = @@ERROR
	RETURN
END


GO
/****** Object:  StoredProcedure [dbo].[p_HolyPromise_Get]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_HolyPromise_Get]
/*
Get holy primise
2008.3 By CJC
 input:
	see SQL
 output:
	nRet > 0 fetch to take data
	= 0 No data
*/
@nCharNo int,
@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT @nRet=COUNT(nUpCharNo) FROM tHolyPromise WHERE nCharNo = @nCharNo
	IF @nRet > 0
	BEGIN
		IF EXISTS(
			SELECT P.nUpCharNo, P.nFlags, P.dRegDate, P.dRejoinableDate, P.dMemberAcceptableDate, C.sID, C.nLevel,C.dLastLoginDate FROM tHolyPromise AS P
			INNER JOIN tCharacter AS C ON C.nCharNo =  P.nUpCharNo AND C.bDeleted = 0
			WHERE P.nCharNo = @nCharNo)
			SELECT P.nUpCharNo, P.nFlags, P.dRegDate, P.dRejoinableDate, P.dMemberAcceptableDate, C.sID, C.nLevel,C.dLastLoginDate FROM tHolyPromise AS P
			INNER JOIN tCharacter AS C ON C.nCharNo =  P.nUpCharNo AND C.bDeleted = 0
			WHERE P.nCharNo = @nCharNo
		ELSE
			SELECT P.nUpCharNo, P.nFlags, P.dRegDate, P.dRejoinableDate, P.dMemberAcceptableDate, '', 1, GetDate() FROM tHolyPromise AS P WHERE P.nCharNo = @nCharNo
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_HolyPromise_GetMember]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_HolyPromise_GetMember]
/*
Get primise member count
2008.3 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int,
@nNumOfMember int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT @nNumOfMember=COUNT( P.nCharNo) FROM tHolyPromise AS P
	INNER JOIN tCharacter AS C ON C.nCharNo =  P.nCharNo AND C.bDeleted = 0
	WHERE P.nUpCharNo = @nCharNo
	IF @nNumOfMember > 0 
	BEGIN
		SELECT P.nCharNo, P.nFlags, P.dRegDate, P.dRejoinableDate, P.dMemberAcceptableDate, C.sID, C.nLevel,C.dLastLoginDate FROM tHolyPromise AS P
		INNER JOIN tCharacter AS C ON C.nCharNo =  P.nCharNo AND C.bDeleted = 0
		WHERE P.nUpCharNo = @nCharNo
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_HolyPromise_GetMemberCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_HolyPromise_GetMemberCount]
/*
Get primise member count
2008.3 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int,
@nNumOfMember int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SET @nNumOfMember = 0
	SELECT @nNumOfMember = COUNT(P.nUpCharNo) FROM tHolyPromise AS P 
	INNER JOIN tCharacter AS C ON C.nCharNo =  P.nCharNo AND C.bDeleted = 0
	WHERE P.nUpCharNo = @nCharNo
END


GO
/****** Object:  StoredProcedure [dbo].[p_HolyPromise_Set]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_HolyPromise_Set]
/*
Holy promise set
2008.4 By CJC
 input:
	see SQL
	
 output:
	@nRet
	0 = OK,  Fiest join
	1 = Ring / same char
	2 = i'm over max member count
	3 = OK, ReJoin
	4 = Failed, Already upper exists
	? = Other DB error code
*/
@nMAXPROMISEMEMBER smallint,
@nCharNo int,
@nUpCharNo int,
@nFlags tinyint,
@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	
	-- check ring, same char.
	EXEC p_HolyPromise_CheckRing @nCharNo, @nUpCharNo, @nRet OUTPUT
	IF @nRet = 1
		RETURN
	
	-- check over max promise and add
	BEGIN TRAN
	DECLARE @nPromiseCount int
	EXEC p_HolyPromise_GetMemberCount @nUpCharNo, @nPromiseCount OUTPUT
	IF @nPromiseCount >= @nMAXPROMISEMEMBER
	BEGIN
		SET @nRet = 2
		ROLLBACK TRAN
		RETURN
	END
	-- Update/Inset data
	IF EXISTS( SELECT nCharNo FROM  tHolyPromise WHERE nCharNo=@nCharNo)
	BEGIN
		-- Check already upper here
		DECLARE @TempUpCharNo int
		SELECT @TempUpCharNo=nUpCharNo FROM  tHolyPromise WHERE nCharNo=@nCharNo
		IF @TempUpCharNo <> 0
		BEGIN
			SET @nRet = 4
			ROLLBACK TRAN
			RETURN
		END
		UPDATE tHolyPromise SET nUpCharNo=@nUpCharNo, nFlags=@nFlags, dRegDate=GetDate() WHERE nCharNo=@nCharNo
		SET @nRet = @@ERROR
		IF @nRet <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN
		END
		SET @nRet = 3 -- OK. Rejoin		
	END
	ELSE
	BEGIN
		INSERT tHolyPromise (  nCharNo,  nUpCharNo,  nFlags )
		VALUES ( @nCharNo, @nUpCharNo, @nFlags )
		SET @nRet = @@ERROR
		IF @nRet <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN
		END
	END
	
	COMMIT TRAN
	RETURN
	-- end
END


GO
/****** Object:  StoredProcedure [dbo].[p_HolyPromise_SetDate]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_HolyPromise_SetDate]
/*
Holy promise set date
2008.4 By CJC
 input:
	see SQL
	
 output:
	@nRet
	0 = OK, 
	? = Other DB error code
*/
@nCharNo int,
@dRejoinableDate datetime,
@dMemberAcceptableDate datetime,
@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	-- Update data
	IF EXISTS( SELECT nCharNo FROM  tHolyPromise WHERE nCharNo=@nCharNo)
	BEGIN
		UPDATE tHolyPromise SET dRejoinableDate=@dRejoinableDate, dMemberAcceptableDate=@dMemberAcceptableDate WHERE nCharNo=@nCharNo
		SET @nRet = @@ERROR
	END
	ELSE	
	BEGIN
		INSERT tHolyPromise (  nCharNo,  nUpCharNo,  nFlags, dRejoinableDate, dMemberAcceptableDate )
		VALUES ( @nCharNo, 0, 0, @dRejoinableDate, @dMemberAcceptableDate )
		SET @nRet = @@ERROR
	END
	
	RETURN
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_BuyAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Item buy all
2004.8 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item owner or Need more owner's money/fame
	        ? = Error code
	        
 operation:
	1. money/fame check and sub
	2. make buy item
' modify kodong 2011.9.9
'	코인으로 아이템 구매시 차감프로시저 추가		
*/
CREATE PROCEDURE [dbo].[p_Item_BuyAll]
	@nItemKey bigint,
	@nOwner int,
	@nStorageType tinyint,
	@nStorage smallint,
	@nItemID int,
	@nFlags int,
	@nPrice bigint,
	@nFame int,
	@nCoin bigint,
	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @CreateItemRet int

	IF @nPrice <= 0 AND @nFame <= 0 AND @nCoin <= 0 BEGIN
		SET @nRet = 2
		RETURN
	END

	BEGIN TRAN
	
	-- 아이템 소유자가 충분한 돈을 가지고 있는지 확인 후 돈 감소
	IF @nPrice > 0 BEGIN
		EXEC p_Char_MoneySub @nOwner, @nPrice, @nRet OUTPUT
		IF @nRet <> 1
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 1
			RETURN
		END
	END
	
	-- 아이템 소유자가 충분한 명성을 가지고 있는지 확인 후 명성 감소
	IF @nFame > 0 BEGIN
		EXEC p_Char_FameSub @nOwner, @nFame, @nRet OUTPUT
		IF @nRet <> 1
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 1
			RETURN
		END
	END
	
	-- 아이템 소유자가 충분한 코인을 가지고 있는지 확인 후 코인 감소
	IF @nCoin > 0 BEGIN
		EXEC usp_Gamble_subCoin @nOwner, @nCoin, @nRet OUTPUT
		IF @nRet <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 1
			RETURN
		END
	END
	
	-- 아이템 생성 저장프로시져 호출
	EXEC p_Item_Create @nItemKey, @nOwner, @nStorageType, @nStorage, @nItemID, @nFlags, @CreateItemRet OUTPUT
	IF @CreateItemRet <> 0 OR @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = @CreateItemRet
		RETURN
	END
	-- 완료
	COMMIT TRAN
	SET @nRet = 0
	-- end
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_BuyLot]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Item buy - change lot and money/fame
2004.8 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item owner or Need more owner's money
	        ? = Error code
	        
 operation:
	1. money/fame check and sub
	2. make buy item
' modify kodong 2011.9.9
'	코인으로 아이템 구매시 차감프로시저 추가	
*/
CREATE PROCEDURE [dbo].[p_Item_BuyLot]
	@nItemKey bigint,
	@nOwner int,
	@nOptionType smallint,
	@nOptionData bigint,
	@nPrice bigint,
	@nFame int,
	@nCoin bigint,
	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON

	IF @nPrice <= 0 AND @nFame <= 0 AND @nCoin <= 0 BEGIN
		SET @nRet = 2
		RETURN
	END

	BEGIN TRAN
	
	-- 아이템 소유자가 충분한 돈을 가지고 있는지 확인 후 돈 감소
	IF @nPrice > 0 BEGIN
		EXEC p_Char_MoneySub @nOwner, @nPrice, @nRet OUTPUT
		IF @nRet <> 1
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 1
			RETURN
		END
	END
	
	-- 아이템 소유자가 충분한 명성을 가지고 있는지 확인 후 명성 감소
	IF @nFame > 0 BEGIN
		EXEC p_Char_FameSub @nOwner, @nFame, @nRet OUTPUT
		IF @nRet <> 1
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 1
			RETURN
		END
	END
	
	-- 아이템 소유자가 충분한 코인을 가지고 있는지 확인 후 코인 감소
	IF @nCoin > 0 BEGIN
		EXEC usp_Gamble_subCoin @nOwner, @nCoin, @nRet OUTPUT
		IF @nRet <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 1
			RETURN
		END
	END
	
	-- 아이템 옵션 저장프로시져 호출(랏 수정)
	EXEC p_Item_SetOption @nItemKey, @nOptionType, @nOptionData, @nRet OUTPUT
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END
	-- 완료
	COMMIT TRAN
	-- end
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_ClrWeaponTitle]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_ClrWeaponTitle]
/*
Item Clear Weapon Title
2006.6 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        1 = Error Not found Weapon mob 
	        2 = Error Clear Weapon mob 
	        3 = Error Delete license item
	        4 = Error Change license item lot
*/
@nWeaponItemKey bigint,
@nMobID smallint,
@nLicenseClearItemKey bigint,
@bLicenseClearItemDelete tinyint,
@nLicenseClearItemOptionType smallint,
@nLicenseClearItemOptionData bigint,
-- Output var
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 아이템에 몹 라이센스 붙어 있는지 확인 
IF NOT EXISTS(SELECT nMobID FROM tItemMobList WHERE nItemKey=@nWeaponItemKey AND nMobID=@nMobID)
BEGIN
	SET @nRet = 1
	RETURN
END
-- 아이템에 몹 라이센스 지우기
BEGIN TRAN
DELETE FROM tItemMobList WHERE nItemKey=@nWeaponItemKey AND nMobID=@nMobID
IF @@ERROR <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 2
	RETURN
END
-- 라이센스 지우는 아이템 지우기/랏조정
DECLARE @nRetTemp int
IF @bLicenseClearItemDelete = 1
BEGIN
	EXEC p_Item_Delete @nLicenseClearItemKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 3
		RETURN
	END
END
ELSE
BEGIN
	EXEC p_Item_SetOption @nLicenseClearItemKey, @nLicenseClearItemOptionType, @nLicenseClearItemOptionData, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
END
-- 성공
COMMIT TRAN
SET @nRet = 0
RETURN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_CostumWeapon_Endure_Set]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_CostumWeapon_Endure_Set]
/*
Item Costum Weapon Endure Set
2008.10 By Lunar
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Not enough money to sub
	        4 = Upgrade value setting, upgrade fail count error(option set error)
	        5 = Raw delete fail
	        6 = RawLeft delete fail, if valid item
	        7 = RawRight delete fail, if valid item
	        8 = RawMiddle delete fail, if valid item
	        
 operation:
	1. money sub
	2. upgrade item level
	3. delete raws
*/
@nCostumWeaponKey bigint,
@nCostumWeaponEndureOptionType smallint,
@nCostumWeaponEndureOptionData bigint,
@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @nTinyintRet tinyint
	DECLARE @nRetTemp int

	BEGIN TRAN

	-- 1 가구 아이템 내구도 상승
	SET @nRetTemp = 1
	EXEC p_Item_SetOption @nCostumWeaponKey, @nCostumWeaponEndureOptionType, @nCostumWeaponEndureOptionData, @nRetTemp OUTPUT
	IF @nRetTemp <> 0 BEGIN
		ROLLBACK TRAN
		SET @nRet = 5
		RETURN
	END
	
	-- 업글 성공
	COMMIT TRAN
	SET @nRet = 0

	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_CostumWeapon_Endure_Update]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_CostumWeapon_Endure_Update]
/*
Item Costum Weapon Endure Update
2008.10 By Lunar
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Not enough money to sub
	        4 = Upgrade value setting, upgrade fail count error(option set error)
	        5 = Raw delete fail
	        6 = RawLeft delete fail, if valid item
	        7 = RawRight delete fail, if valid item
	        8 = RawMiddle delete fail, if valid item
	        
 operation:
	1. money sub
	2. upgrade item level
	3. delete raws
*/
@nOwner int,
@nEndureKitKey bigint,
@nEndureKitOptionType smallint,
@nEndureKitLot smallint,
@nCostumWeaponKey bigint,
@nCostumWeaponEndureOptionType smallint,
@nCostumWeaponEndureOptionData bigint,
@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @nTinyintRet tinyint
	DECLARE @nRetTemp int

	-- 1.1 내구도 키트 아이템 소유자 확인
	EXEC p_Item_IsValidOwner @nEndureKitKey, @nOwner, @nTinyintRet OUTPUT
	IF @nTinyintRet <> 0 BEGIN
		SET @nRet = @nTinyintRet
		RETURN
	END
	
	-- 1.2 무기 코스튬 아이템 소유자 확인
	EXEC p_Item_IsValidOwner @nCostumWeaponKey, @nOwner, @nTinyintRet OUTPUT
	IF @nTinyintRet <> 0 BEGIN
		SET @nRet = @nTinyintRet
		RETURN
	END

	BEGIN TRAN
	
	-- 2.1 사용된 내구도 키트 아이템 지우기 (사용후 Lot == 0 인 경우)
	IF @nEndureKitLot = 0 BEGIN
		SET @nRetTemp = 1
		EXEC p_Item_Delete @nEndureKitKey, @nRetTemp OUTPUT
		IF @nRetTemp <> 0 BEGIN
			ROLLBACK TRAN
			SET @nRet = 5
			RETURN
		END
	END
	-- 2.2 사용된 내구도 키트 아이템 차감하기 (사용후 Lot > 0 인 경우)
	ELSE BEGIN
		SET @nRetTemp = 1
		EXEC p_Item_SetOption @nEndureKitKey, @nEndureKitOptionType, @nEndureKitLot, @nRetTemp OUTPUT
		IF @nRetTemp <> 0 BEGIN
			ROLLBACK TRAN
			SET @nRet = 5
			RETURN
		END
	END
	
	-- 3 가구 아이템 내구도 상승
	SET @nRetTemp = 1
	EXEC p_Item_SetOption @nCostumWeaponKey, @nCostumWeaponEndureOptionType, @nCostumWeaponEndureOptionData, @nRetTemp OUTPUT
	IF @nRetTemp <> 0 BEGIN
		ROLLBACK TRAN
		SET @nRet = 5
		RETURN
	END
	
	-- 업글 성공
	COMMIT TRAN
	SET @nRet = 0

	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Create]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Item Create
2004.8 By CJC
2010.12.27 By kodong
'	아이템테이블의 UNIQUE 제약조건 제거로 인해 해당 스토리지에 
'	아이템이 이미 존재하는지 체크하는 프로세스 추가
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
CREATE PROCEDURE [dbo].[p_Item_Create]
	@nItemKey bigint
,	@nOwner int
,	@nStorageType tinyint
,	@nStorage smallint
,	@nItemID int
,	@nFlags int
,	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	IF EXISTS(SELECT nItemKey 
				FROM tItem 
			   WHERE nOwner = @nOwner 
				 AND nStorageType = @nStorageType 
				 AND nStorage = @nStorage
				 AND nFlags = 0) BEGIN
		SET @nRet = -2
	END
	ELSE BEGIN
		INSERT tItem (  nItemKey,  nOwner,  nStorageType,  nStorage,  nItemID,  nFlags )
		VALUES       ( @nItemKey, @nOwner, @nStorageType, @nStorage, @nItemID, @nFlags )
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -9
		END
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Create_UseEmptyStorage]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Item Create
2008.4 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
CREATE PROCEDURE [dbo].[p_Item_Create_UseEmptyStorage]
	@nItemKey bigint
,	@nOwner int
,	@nStorageType tinyint
,	@nStorage smallint OUTPUT
,	@nItemID int
,	@nFlags int
,	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON

	-- 빈인벤 위치찾기
	EXEC p_Item_GetStorageEmpty @nOwner, @nStorageType, @nStorage OUTPUT
	IF @nStorage < 0
	BEGIN
		SET @nRet = -1
		RETURN
	END

	-- 2010.12.29 By kodong
	-- 아이템테이블의 UNIQUE 제약조건 제거로 인해 해당 스토리지에 아이템이 이미 존재하는지 체크하는 프로세스 추가
	EXEC p_Item_Create @nItemKey, @nOwner, @nStorageType, @nStorage, @nItemID, @nFlags, @nRet output
	IF @nRet <> 0 BEGIN
		SET @nRet = -2
	END
	ELSE BEGIN
		SET @nRet = 0
	END
	/*
	-- 아이템 생성
	INSERT tItem (  nItemKey,  nOwner,  nStorageType,  nStorage,  nItemID,  nFlags )
	VALUES       ( @nItemKey, @nOwner, @nStorageType, @nStorage, @nItemID, @nFlags )
	SET @nRet = @@ERROR
	IF @nRet = 0
		COMMIT TRAN
	ELSE
		ROLLBACK TRAN
	*/
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Delete]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_Delete]
/*
Item Delete
2004.8 By CJC
 input:
	nItemKey = To be delete.
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nItemKey bigint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 아이템 삭제 옵션
DELETE FROM tItem WHERE nItemKey = @nItemKey
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_ExchangeStorage]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_ExchangeStorage]
/*
Exchange item storage
2004.8 By CJC
 input:
	nItemKey1,nStorageType1,nStoage1 = #1 Item
	nItemKey2,nStorageType2,nStoage2 = #2 Item
 output:
	0 = Ok
	1~3 = Error step No.
 operation:
	Set nItemKey1 To nStorageType1,nStoage1
	Set nItemKey2 To nStorageType2,nStoage2
	
	1. #1 item move to temp storage   * #1,#2 is already input that exchanged data.
	2. set #2's storage to #2
	3. set #1's storage to #1
*/
@nItemKey1 bigint,
@nStorageType1 tinyint,
@nStorage1 smallint,
@nItemKey2 bigint,
@nStorageType2 tinyint,
@nStorage2 smallint,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
SET @nRet = 0
BEGIN TRAN
-- Step 1
UPDATE tItem SET nStorageType = 11
WHERE nItemKey = @nItemKey1
IF @@ROWCOUNT = 0
BEGIN
	SET @nRet = 1
	ROLLBACK TRAN
	RETURN
END
	
-- Step 2
UPDATE tItem SET nStorageType = @nStorageType2, nStorage = @nStorage2
WHERE nItemKey = @nItemKey2
IF @@ROWCOUNT = 0
BEGIN
	SET @nRet = 2
	ROLLBACK TRAN
	RETURN
END
	
-- Step 3
UPDATE tItem SET nStorageType = @nStorageType1, nStorage = @nStorage1
WHERE nItemKey = @nItemKey1
IF @@ROWCOUNT = 0
BEGIN
	SET @nRet = 3
	ROLLBACK TRAN
	RETURN
END
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_ExchangeStorageAndOwner]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_ExchangeStorageAndOwner]
/*
Exchange item storage
2004.8 By CJC
 input:
	nOwner1,nItemKey1,nStorageType1,nStoage1 = #1 Item
	nOwner2,nItemKey2,nStorageType2,nStoage2 = #2 Item
 output:
	0 = Ok
	1~3 = Error step No.
 operation:
	Set nItemKey1 To nOwner1,nStorageType1,nStoage1
	Set nItemKey2 To nOwner2,nStorageType2,nStoage2
	
	1. #1 item move to temp storage   * #1,#2 is already input that exchanged data.
	2. set #2's storage to #2
	3. set #1's storage to #1
*/
@nItemKey1 bigint,
@nOwner1 int,
@nStorageType1 tinyint,
@nStorage1 smallint,
@nItemKey2 bigint,
@nOwner2 int,
@nStorageType2 tinyint,
@nStorage2 smallint,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
SET @nRet = 0
BEGIN TRAN
-- Step 1
UPDATE tItem SET nStorageType = 11
WHERE nItemKey = @nItemKey1
IF @@ROWCOUNT = 0
BEGIN
	SET @nRet = 1
	ROLLBACK TRAN
	RETURN
END
	
-- Step 2
UPDATE tItem SET nStorageType = @nStorageType2, nStorage = @nStorage2, nOwner = @nOwner2
WHERE nItemKey = @nItemKey2
IF @@ROWCOUNT = 0
BEGIN
	SET @nRet = 2
	ROLLBACK TRAN
	RETURN
END
	
-- Step 3
UPDATE tItem SET nStorageType = @nStorageType1, nStorage = @nStorage1, nOwner = @nOwner1
WHERE nItemKey = @nItemKey1
IF @@ROWCOUNT = 0
BEGIN
	SET @nRet = 3
	ROLLBACK TRAN
	RETURN
END
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Furniture_Endure_Update]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_Furniture_Endure_Update]
/*
Item Furniture Endure Update
2008.10 By Lunar
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Not enough money to sub
	        4 = Upgrade value setting, upgrade fail count error(option set error)
	        5 = Raw delete fail
	        6 = RawLeft delete fail, if valid item
	        7 = RawRight delete fail, if valid item
	        8 = RawMiddle delete fail, if valid item
	        
 operation:
	1. money sub
	2. upgrade item level
	3. delete raws
*/
@nOwner int,
@nEndureKitKey bigint,
@nEndureKitOptionType smallint,
@nEndureKitLot smallint,
@nFurnitureKey bigint,
@nFurnitureEndureOptionType smallint,
@nFurnitureEndureOptionData bigint,
@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @nTinyintRet tinyint
	DECLARE @nRetTemp int

	-- 1.1 내구도 키트 아이템 소유자 확인
	EXEC p_Item_IsValidOwner @nEndureKitKey, @nOwner, @nTinyintRet OUTPUT
	IF @nTinyintRet <> 0 BEGIN
		SET @nRet = @nTinyintRet
		RETURN
	END
	
	-- 1.2 가구 아이템 소유자 확인
	EXEC p_Item_IsValidOwner @nFurnitureKey, @nOwner, @nTinyintRet OUTPUT
	IF @nTinyintRet <> 0 BEGIN
		SET @nRet = @nTinyintRet
		RETURN
	END

	BEGIN TRAN
	
	-- 2.1 사용된 내구도 키트 아이템 지우기 (사용후 Lot == 0 인 경우)
	IF @nEndureKitLot = 0 BEGIN
		SET @nRetTemp = 1
		EXEC p_Item_Delete @nEndureKitKey, @nRetTemp OUTPUT
		IF @nRetTemp <> 0 BEGIN
			ROLLBACK TRAN
			SET @nRet = 5
			RETURN
		END
	END
	-- 2.2 사용된 내구도 키트 아이템 차감하기 (사용후 Lot > 0 인 경우)
	ELSE BEGIN
		SET @nRetTemp = 1
		EXEC p_Item_SetOption @nEndureKitKey, @nEndureKitOptionType, @nEndureKitLot, @nRetTemp OUTPUT
		IF @nRetTemp <> 0 BEGIN
			ROLLBACK TRAN
			SET @nRet = 5
			RETURN
		END
	END
	
	-- 3 가구 아이템 내구도 상승
	SET @nRetTemp = 1
	EXEC p_Item_SetOption @nFurnitureKey, @nFurnitureEndureOptionType, @nFurnitureEndureOptionData, @nRetTemp OUTPUT
	IF @nRetTemp <> 0 BEGIN
		ROLLBACK TRAN
		SET @nRet = 5
		RETURN
	END
	
	-- 업글 성공
	COMMIT TRAN
	SET @nRet = 0

	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetData]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetData]
/*
Item Get Data
2004.10 By CJC
 input:
	nItemKey = Item Key
 output:
	@nRet	1 = OK, 
	        0 = Error
*/
@nItemKey bigint,
@nOwner int OUTPUT,
@nStorageType tinyint OUTPUT,
@nStorage smallint OUTPUT,
@nItemID int OUTPUT,
@nFlags int OUTPUT,
@dDate datetime OUTPUT,
@nRet int OUTPUT
AS
SET NOCOUNT ON
SET @nRet = 0
SELECT 
	@nOwner = nOwner,
	@nStorageType = nStorageType,
	@nStorage = nStorage,
	@nItemID = nItemID,
	@nFlags = nFlags,
	@dDate = dDate
FROM tItem
WHERE nItemKey = @nItemKey
SET @nRet = @@ROWCOUNT
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetList]
/*
Item Get list
2004.8 By CJC
 input:
	nCharNo	     = Item Owner
 output:
	none
 desc:
	fetch success, get data
	fetch fail, not data
*/
@nCharNo int
AS
SET NOCOUNT ON
SELECT nItemKey, nStorageType, nStorage, nItemID, nFlags, dDate
FROM tItem
WHERE nOwner = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetListType]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetListType]
/*
Item Get list from StorageType
2004.8 By CJC
 input:
	nCharNo	     = Item Owner
	nStorageType = Item Storage Type
 output:
	none
 desc:
	fetch success, get data
	fetch fail, not data
*/
@nCharNo int,
@nStorageType tinyint
AS
SET NOCOUNT ON
SELECT nItemKey, nStorage, nItemID, nFlags, dDate
FROM tItem WITH(READUNCOMMITTED) 
WHERE nOwner = @nCharNo	AND nStorageType = @nStorageType
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetMobList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetMobList]
/*
Item Get Mob List
2004.8 By CJC
 input:
	see SQL
 output:
	@nRet	0 = No data fount
	        ? = Number data here(must to be 1)
	        
	@nGrade = grade
	@nKillCount = kill count(progress)
		        
*/
@nItemKey bigint,
@nMobID smallint,
-- Output var
@nGrade tinyint OUTPUT,
@nKillCount int OUTPUT,
@nRet int OUTPUT
AS
SET NOCOUNT ON
SELECT @nGrade = nGrade, @nKillCount = nKillCount 
FROM tItemMobList
WHERE nItemKey = @nItemKey AND nMobID = @nMobID
SET @nRet = @@ROWCOUNT
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetMobListAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetMobListAll]
/*
Item Get Mob List All
2004.8 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nItemKey bigint
AS
SET NOCOUNT ON
SELECT nMobID, nGrade, nKillCount FROM tItemMobList WHERE nItemKey = @nItemKey
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetNumOfItem]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetNumOfItem]
/*
Get number of item
2004.8 By CJC
 input:
	nCharNo	    = Item Owner
 output:
	nItemCount,	-1 = error
	             ? = Count of item;
*/
@nCharNo int,
@nNumOfItem int OUTPUT
AS
SET NOCOUNT ON
SET @nNumOfItem = -1
SELECT @nNumOfItem = COUNT(*) FROM tItem WHERE nOwner = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetOption]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetOption]
/*
Item Get Option
2004.8 By CJC
 input:
	see SQL
 output:
	@nRet	0 = No data found
	        ? = Number data here(must to be 1)
	        
	@nOptionData = option data
		        
*/
@nItemKey bigint,
@nOptionType smallint,
-- Output var
@nOptionData bigint OUTPUT,
@nRet int OUTPUT
AS
SET NOCOUNT ON
SELECT @nOptionData = nOptionData FROM tItemOptions WHERE nItemKey = @nItemKey AND nOptionType = @nOptionType
SET @nRet = @@ROWCOUNT
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetOptionAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetOptionAll]
/*
Item Get Option All
2004.8 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nItemKey bigint
AS
SET NOCOUNT ON
SELECT nOptionType, nOptionData FROM tItemOptions WHERE nItemKey = @nItemKey
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetOptionCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetOptionCount]
/*
Item Get Option Count
2004.8 By CJC
 input:
	see SQL
 output:
	@nOptionCount = Item option count
*/
@nItemKey bigint,
@nOptionCount int OUTPUT
AS
SET NOCOUNT ON
SELECT @nOptionCount = COUNT(nItemKey) FROM tItemOptions WHERE nItemKey = @nItemKey
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetStorage]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetStorage]
/*
Get item storage
2004.8 By CJC
 input:
	nItemKey	 = Item Key
 output:
	1, ok nStorageType, nStorage = valid value
	0, Not found item
*/
@nItemKey bigint,
@nStorageType tinyint OUTPUT,
@nStorage smallint OUTPUT,
@nRet tinyint = 1 OUTPUT 
AS
SET NOCOUNT ON
SELECT @nStorageType = nStorageType, @nStorage = nStorage FROM tItem WHERE nItemKey = @nItemKey
-- Check not found item
IF @@ROWCOUNT <> 1
	SET @nRet = 0
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetStorageAndOwner]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetStorageAndOwner]
/*
Get item storage
2004.8 By CJC
 input:
	nItemKey	 = Item Key
 output:
	1, ok nOwner, nStorageType, nStorage = valid value
	0, Not found item
*/
@nItemKey bigint,
@nOwner int OUTPUT,
@nStorageType tinyint OUTPUT,
@nStorage smallint OUTPUT,
@nRet tinyint OUTPUT 
AS
SET NOCOUNT ON
SELECT @nOwner = nOwner, @nStorageType = nStorageType, @nStorage = nStorage FROM tItem WHERE nItemKey = @nItemKey
-- Check not found item
IF @@ROWCOUNT <> 1
	SET @nRet = 0
ELSE
	SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetStorageEmpty]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Item_getEmptyStorage
' 작성자 : 고동균(kodong@gmail.com)
' 작성일 : 2008.4.1
' Description 
'   owner와 storageType을 받아 빈공간의 storage번호를 리턴하는 프로시저
' Parameter 
'	input Parameter
'		@owner       : 캐릭터번호
'		@storageType : 저장소
'	output Parameter
'		@ret         : result
'			<  0 : fail
'			>= 0 : empty storage number
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[p_Item_GetStorageEmpty]
	@owner       int = 0
,	@storageType tinyint = 0
,	@ret         int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @err AS bit
	DECLARE @emptyStorage AS smallint
	SET @err = 0
	IF @owner = 0
		SET @err = 1
	IF @storageType = 0
		SET @err = 1
	IF @err <> 1
		BEGIN	
			IF EXISTS(SELECT nItemKey FROM tItem WHERE nOwner = @owner AND nStorageType = @storageType AND nStorage = 0)
				BEGIN
					SELECT @emptyStorage = ISNULL(MIN(nStorage + 1), 0)
					  FROM tItem 
					 WHERE nOwner = @owner 
					   AND nStorageType = @storageType 
					   AND nStorage + 1 NOT IN (
							SELECT nStorage
							  FROM tItem 
							 WHERE nOwner = @owner AND nStorageType = @storageType)
				END
			ELSE
				BEGIN
					SET @emptyStorage = 0
				END
			SET @ret = @emptyStorage
			PRINT @ret
		END
	ELSE
		SET @ret = -1
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetStorageEmptyList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 프로시져

/*--------------------------------------------------------------------------------------
' 이  름 : p_Item_GetStorageEmptyList
' 작성자 :
' 작성일 : 2009.9.14
' Description :
'   특정 소유자의 임의의 인벤토리 내에서 비어있는 위치를 0번부터 원하는 갯수만큼 가져온다.
'   0 ~ 65535 사이의 인벤토리만을 가져오기 때문에 이에 대해 숙지하고 있어야 한다.
'--------------------------------------------------------------------------------------
'   임시 테이블을 쓰는 방식대신 Index 걸린 테이블을 만들어 두는 방식으로 결정
'	-- 0 ~ 65535 까지 순서대로 데이터를 가질 임시 테이블 생성
'	IF OBJECT_ID('tempdb..#TEMP_ITEM_STORAGE') IS NULL
'	BEGIN
'		CREATE TABLE #TEMP_ITEM_STORAGE (
'			nStorage int
'		)
'
'		DECLARE @i as int
'		SET @i = 0
'		WHILE (@i <= 65535) BEGIN
'			INSERT #TEMP_ITEM_STORAGE VALUES (@i)
'
'			SET @i = @i + 1
'		END
'	END
'-------------------------------------------------------------------------------------
' Parameter :
'	input Parameter
'		@nOwner         : 소유주 번호
'		@nStorageType   : 인벤토리 타입
'		@nGetStorageCnt : 원하는 빈셀 갯수
'	output Parameter
'		@nRet	         : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-1000 : invaild @nOwner
'				-1000 : 
'	return Record
'		nCount
'		nTotalDividend
'-------------------------------------------------------------------------------------*/
CREATE  PROCEDURE [dbo].[p_Item_GetStorageEmptyList]
	@nOwner         int
,	@nStorageType   int
,	@nGetStorageCnt int = 1
,	@nRet           int = 0 output
AS
BEGIN
	SET NOCOUNT ON

	SET @nRet = 0

	IF @nOwner = -1 BEGIN
		SET @nRet = -1000
		RETURN
	END

	-- 동적 쿼리 작성 시작
	DECLARE @SQL AS NVARCHAR(3000)
	DECLARE @PARAMS AS NVARCHAR(1000)
	SET @SQL = N''
	SET @PARAMS = N''


	SET @SQL = N'
		SELECT TOP ' + CAST(@nGetStorageCnt AS NVARCHAR) + ' A.nStorage
		FROM tItemStorageFindEmpty A LEFT OUTER JOIN (
			SELECT nStorage
			FROM tItem
			WHERE nOwner = ' + CAST(@nOwner AS NVARCHAR) + '
			AND nStorageType = ' + CAST(@nStorageType AS NVARCHAR) + ') B ON A.nStorage = B.nStorage
		WHERE B.nStorage IS NULL
		ORDER BY A.nStorage'
	SET @PARAMS = '@nGetStorageCnt INT, @nOwner INT, @nStorageType INT'

	-- 만들어진 동적 쿼리 실행
	EXEC sp_executesql @SQL, @PARAMS, @nGetStorageCnt, @nOwner, @nStorageType

	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetStorageListType]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetStorageListType]
/*
Item Get storage list from StorageType
2004.8 By CJC
 input:
	nCharNo	     = Item Owner
	nStorageType = Item Storage Type
 output:
	none
 desc:
	fetch success, get data
	fetch fail, not data
*/
@nCharNo int,
@nStorageType tinyint
AS
SET NOCOUNT ON
SELECT nStorage FROM tItem WHERE nOwner = @nCharNo AND nStorageType = @nStorageType
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetStorageTypeCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetStorageTypeCount]
/*
Item Get number of item count from StorageType
2008.4 By CJC
 input:
	Item Owner
	Item StorageType
 output:
	Number of item count from StorageType
 */
@nOwner int,
@nStorageType tinyint,
@nItemCount int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SELECT @nItemCount=COUNT(nOwner) FROM tItem WHERE nOwner = @nOwner AND nStorageType = @nStorageType
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_GetTitle]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_GetTitle]
/*
Item Get Title
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	0 = No data fount
	        ? = Number data here(must to be 1)
	        
	@nTitleType,@nTitleCharNo,@sTitle = title data
		        
*/
@nItemKey bigint,
-- Output var
@nTitleType smallint OUTPUT,
@nTitleCharNo int OUTPUT,
@sTitle nvarchar(24) OUTPUT,
@nRet int OUTPUT
AS
SET NOCOUNT ON

IF EXISTS(SELECT nItemKey FROM tItemTitle WHERE nItemKey = @nItemKey)
BEGIN
	SELECT 
	@nTitleType = nTitleType,
	@nTitleCharNo = nTitleCharNo,
	@sTitle = sTitle
	FROM tItemTitle WHERE nItemKey = @nItemKey
SELECT 5555
	SET @nRet = @@ROWCOUNT
END
ELSE
BEGIN
	SET @nTitleType = 0
	SET @nTitleCharNo = 0
	SET @sTitle = ''
	SET @nRet = 0
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_IsValidOwner]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_IsValidOwner]
/*
Is valid item owner ?
2004.8 By CJC
 input:
	nItemKey	 = Item Key
	nOwner	     = Item Owner
 output:
	0 = OK
	1 = Not found item
	2 = Missmatch item owner
*/
@nItemKey bigint,
@nOwner int,
@nRet tinyint OUTPUT 
AS
SET NOCOUNT ON
DECLARE @nDBOwner int 
SET @nDBOwner = 0
SET @nRet = 0
SELECT @nDBOwner = nOwner FROM tItem WITH (READUNCOMMITTED) WHERE nItemKey = @nItemKey
-- Check not found item
IF @@ROWCOUNT <> 1
BEGIN
	SET @nRet = 1
	RETURN
END
-- Check missmatch item owner
IF @nDBOwner <> @nOwner
BEGIN
	SET @nRet = 2
	RETURN
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Merge]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_Merge]
/*
Item Merge - change lot and delete item
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found from item
	        2 = Missmatch from item owner
	        3 = Not found to item
	        4 = Missmatch to item owner
	        ? = Error code(Lot change/Delete item error)
*/
@nOwnerFrom int,
@nOwnerTo int,
@nItemKeyFrom bigint,
@nItemKeyTo bigint,
@nOptionType smallint,
@nOptionData bigint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 삭제될 아이템(From) 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKeyFrom, @nOwnerFrom, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END
-- 랏 변경될 아이템(To) 소유자 확인
EXEC p_Item_IsValidOwner @nItemKeyTo, @nOwnerTo, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet + 2
	RETURN
END
BEGIN TRAN
-- 아이템 랏 변경저장프로시져 호출
EXEC p_Item_SetOption @nItemKeyTo, @nOptionType, @nOptionData, @nRet OUTPUT
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN
	RETURN
END
-- 아이템 삭제
EXEC p_Item_Delete @nItemKeyFrom, @nRet OUTPUT
IF @@ERROR <> 0
BEGIN
	ROLLBACK TRAN
	RETURN
END
-- 완료
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Merge_New]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_Merge_New]
/*
Item Merge - change lot and delete item
2007.11 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found from item
	        2 = Missmatch from item owner
	        3 = Not found to item
	        4 = Missmatch to item owner
                     5 = Get Sub Lot Failed
                     6 = Get Existed Lot Failed
                     7 = Set new lot failed
                     8 = Delete item failed
*/
@nOwnerFrom int,
@nOwnerTo int,
@nItemKeyFrom bigint,
@nItemKeyTo bigint,
@nOptionType smallint,
@nOptionDataLotSub bigint OUTPUT,
@nOptionDataLotResult bigint OUTPUT,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 삭제될 아이템(From) 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKeyFrom, @nOwnerFrom, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END
-- 랏 변경될 아이템(To) 소유자 확인
EXEC p_Item_IsValidOwner @nItemKeyTo, @nOwnerTo, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet + 2
	RETURN
END
-- 빼질 아이템 랏 얻기
EXEC p_Item_GetOption @nItemKeyFrom, @nOptionType, @nOptionDataLotSub OUTPUT, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	SET @nRet = 5
	RETURN
END
-- 더해질 아이템 랏 얻기
DECLARE @nOptionDataLotAdd bigint
EXEC p_Item_GetOption @nItemKeyTo, @nOptionType, @nOptionDataLotAdd OUTPUT, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	SET @nRet = 6
	RETURN
END
-- 아이템 랏 변경저장프로시져 호출
BEGIN TRAN
SET @nOptionDataLotResult = @nOptionDataLotSub + @nOptionDataLotAdd
EXEC p_Item_SetOption @nItemKeyTo, @nOptionType, @nOptionDataLotResult, @nRet OUTPUT
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 7
	RETURN
END
-- 아이템 삭제
EXEC p_Item_Delete @nItemKeyFrom, @nRet OUTPUT
IF @@ERROR <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 8
	RETURN
END
-- 완료
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_MiniHouse_Effect_Resource_Del]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_MiniHouse_Effect_Resource_Del]
/*
Item MiniHouse Effect Resource Del 
2008.3 By Lunar
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Effect Resource Item delete fail, if valid item
	        4 = Effect Resource Item Lot value setting error
	        5 = Not enough money to sub
*/
@nOwner int,
@nNeedMoney bigint,
@nNeedItemKey bigint,
@nNeedItemOptionType smallint,
@nNeedItemLot int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
DECLARE @nTinyintRet tinyint
DECLARE @nRetTemp int
BEGIN TRAN
-- 사용된 자원 아이템 지우기
IF @nNeedItemKey <> 0
BEGIN
	-- 아이템 소유자 확인
	EXEC p_Item_IsValidOwner @nNeedItemKey, @nOwner, @nTinyintRet OUTPUT
	IF @nTinyintRet <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 1
		RETURN
	END
	IF @nNeedItemLot = 1
	BEGIN
		SET @nRetTemp = 1
		EXEC p_Item_Delete @nNeedItemKey, @nRetTemp OUTPUT
		IF @nRetTemp <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 2
			RETURN
		END
	END
	IF @nNeedItemLot > 1
	BEGIN
		SET @nRetTemp = 1
		SET @nNeedItemLot = @nNeedItemLot - 1
		EXEC p_Item_SetOption @nNeedItemKey, @nNeedItemOptionType, @nNeedItemLot, @nRetTemp OUTPUT
		IF @nRetTemp <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 3
			RETURN
		END
	END
END
-- 아이템 소유자의 돈 감소
IF @nNeedMoney > 0 -- 수고비가 있는 경우, 금액을 빼준다.
BEGIN
	EXEC p_Char_MoneySub @nOwner, @nNeedMoney, @nTinyintRet OUTPUT
	IF @nTinyintRet <> 1
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
END
-- 업글 성공
COMMIT TRAN
SET @nRet = 0
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SellAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_SellAll]
/*
Item sell all
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Money add error
	        ? = Error code
	        
 operation:
	1. money add
	2. delete sell item
	
*/
@nItemKey bigint,
@nOwner int,
@nPrice bigint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 아이템 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKey, @nOwner, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END
-- 아이템 소유자의 돈 증가
BEGIN TRAN
EXEC p_Char_MoneyAdd @nOwner, @nPrice, @nTinyintRet OUTPUT
IF @nTinyintRet <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 3
	RETURN
END
-- 아이템 삭제 저장프로시져 호출
EXEC p_Item_Delete @nItemKey, @nRet OUTPUT
IF @@ERROR <> 0
BEGIN
	ROLLBACK TRAN
	RETURN
END
-- 완료
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SellAll_LotCheck]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_SellAll_LotCheck]
/*
Item sell all
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Money add error
	        ? = Error code
	        
 operation:
	1. money add
	2. delete sell item
	
*/
@nItemKey bigint,
@nOwner int,
@nOptionType smallint,
@nLot bigint,
@nPrice bigint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 아이템 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKey, @nOwner, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END

-- 1보다 큰 경우에만 Lot 을 체크해 본다.
-- 1일 경우는 어차피 tItem 테이블에 존재하는 것만으로도 옳은 것으로 취급한다.
IF @nLot > 1
BEGIN
	DECLARE @nGetOptionDataLot bigint
	DECLARE @nGetOptionRet int
	EXEC p_Item_GetOption @nItemKey, @nOptionType, @nGetOptionDataLot OUTPUT, @nGetOptionRet OUTPUT
	IF @nGetOptionRet <> 1
	BEGIN
		SET @nRet = 4
		RETURN
	END

	IF @nGetOptionDataLot < @nLot
	BEGIN
		SET @nRet = 5
		RETURN
	END
END

-- 아이템 소유자의 돈 증가
BEGIN TRAN
EXEC p_Char_MoneyAdd @nOwner, @nPrice, @nTinyintRet OUTPUT
IF @nTinyintRet <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 3
	RETURN
END
-- 아이템 삭제 저장프로시져 호출
EXEC p_Item_Delete @nItemKey, @nRet OUTPUT
IF @@ERROR <> 0
BEGIN
	ROLLBACK TRAN
	RETURN
END
-- 완료
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SellLot]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_SellLot]
/*
Item sell - change lot and add money
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Money add error
	        ? = Error code(Lot change error)
*/
@nItemKey bigint,
@nOwner int,
@nOptionType smallint,
@nOptionData bigint,
@nPrice bigint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 아이템 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKey, @nOwner, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END
BEGIN TRAN
-- 아이템 소유자가 돈 증가
EXEC p_Char_MoneyAdd @nOwner, @nPrice, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 3
	RETURN
END
-- 아이템 랏 저장프로시져 호출
EXEC p_Item_SetOption @nItemKey, @nOptionType, @nOptionData, @nRet OUTPUT
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN
	RETURN
END
-- 완료
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SellLot_LotCheck]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_SellLot_LotCheck]
/*
Item sell - change lot and add money
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Money add error
	        ? = Error code(Lot change error)
*/
@nItemKey bigint,
@nOwner int,
@nOptionType smallint,
@nOptionData bigint,
@nPrice bigint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 아이템 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKey, @nOwner, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END

DECLARE @nGetOptionDataLot bigint
DECLARE @nGetOptionRet int
EXEC p_Item_GetOption @nItemKey, @nOptionType, @nGetOptionDataLot OUTPUT, @nGetOptionRet OUTPUT
IF @nGetOptionRet <> 1
BEGIN
	SET @nRet = 4
	RETURN
END

IF @nGetOptionDataLot < @nOptionData
BEGIN
	SET @nRet = 5
	RETURN
END

BEGIN TRAN
-- 아이템 소유자가 돈 증가
EXEC p_Char_MoneyAdd @nOwner, @nPrice, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	ROLLBACK TRAN
	SET @nRet = 3
	RETURN
END
-- 아이템 랏 저장프로시져 호출
EXEC p_Item_SetOption @nItemKey, @nOptionType, @nOptionData, @nRet OUTPUT
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN
	RETURN
END
-- 완료
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SetData]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Item Set data
2004.10 By CJC
2010.12.27 By kodong
'	아이템테이블의 UNIQUE 제약조건 제거로 인해 해당 스토리지에 
'	아이템이 이미 존재하는지 체크하는 프로세스 추가
 input:
	see SQL
 output:
	@nRet	1 = OK, 
	        0 = Error
*/
CREATE PROCEDURE [dbo].[p_Item_SetData]
	@nItemKey bigint
,	@nOwner int
,	@nStorageType tinyint
,	@nStorage smallint
,	@nItemID int
,	@nFlags int
,	@dDate datetime
,	@nRet int OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000
	
	SET @nRet = 0

	IF EXISTS(SELECT nItemKey 
				FROM tItem 
			   WHERE nOwner = @nOwner 
				 AND nStorageType = @nStorageType 
				 AND nStorage = @nStorage
				 AND nFlags = 0) BEGIN
		SET @nRet = 0
	END
	ELSE BEGIN
		BEGIN TRAN
		
		UPDATE tItem 
		   SET nOwner = @nOwner
			 , nStorageType = @nStorageType
			 , nStorage = @nStorage
			 , nItemID = @nItemID
			 , nFlags = @nFlags
			 , dDate = @dDate
		 WHERE nItemKey = @nItemKey
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			SET @nRet = 0
			ROLLBACK TRAN
		END
		ELSE BEGIN
			SET @nRet = 1
			COMMIT TRAN
		END
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SetMobList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_SetMobList]
/*
Item Set Mob List
2004.8 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nItemKey bigint,
@nMobID smallint,
@nGrade tinyint,
@nKillCount int,
-- Output var
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tItemMobList SET	nGrade = @nGrade, nKillCount = @nKillCount
WHERE nItemKey = @nItemKey AND nMobID = @nMobID
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tItemMobList (  nItemKey,  nMobID,  nGrade,  nKillCount )
	VALUES				( @nItemKey, @nMobID, @nGrade, @nKillCount )
END
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SetOption]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_SetOption]
/*
Item Set Option
2004.8 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nItemKey bigint,
@nOptionType smallint,
@nOptionData bigint,
-- Output var
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tItemOptions SET	nOptionData = @nOptionData
WHERE nItemKey = @nItemKey AND nOptionType = @nOptionType
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tItemOptions (  nItemKey,  nOptionType,   nOptionData )
	VALUES				( @nItemKey, @nOptionType,  @nOptionData )
END
SET @nRet = @@ERROR
-- end
RETURN


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SetStorage]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Get item storage
2004.8 By CJC
2010.12.27 By kodong
'	아이템테이블의 UNIQUE 제약조건 제거로 인해 해당 스토리지에 
'	아이템이 이미 존재하는지 체크하는 프로세스 추가
 input:
	nItemKey	 = Item Key
	nStorageType, nStorage = Storage new value
 output:
	1 = OK
	0 = Not found or error
*/
CREATE PROCEDURE [dbo].[p_Item_SetStorage]
	@nItemKey bigint
,	@nStorageType tinyint
,	@nStorage smallint
,	@nRet tinyint OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000

	DECLARE @owner int
	
	SELECT @owner = nOwner FROM tItem WHERE nItemKey = @nItemKey 
	IF EXISTS(SELECT nItemKey 
				FROM tItem 
			   WHERE nOwner = @owner 
				 AND nStorageType = @nStorageType 
				 AND nStorage = @nStorage
				 AND nFlags = 0) BEGIN
		SET @nRet = 0
	END
	ELSE BEGIN	
		BEGIN TRAN
		
		UPDATE tItem 
		   SET nStorageType = @nStorageType, nStorage = @nStorage
		 WHERE nItemKey = @nItemKey
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			ROLLBACK TRAN
			SET @nRet = 0
		END
		ELSE BEGIN
			COMMIT TRAN
			SET @nRet = 1
		END
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SetStorageAndOwner]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Get item storage
2004.8 By CJC
2010.12.27 By kodong
'	아이템테이블의 UNIQUE 제약조건 제거로 인해 해당 스토리지에 
'	아이템이 이미 존재하는지 체크하는 프로세스 추가
 input:
	nItemKey	 = Item Key
	nOwner, nStorageType, nStorage = Storage new value
 output:
	1 = OK
	0 = Not found or error
*/
CREATE PROCEDURE [dbo].[p_Item_SetStorageAndOwner]
	@nItemKey bigint
,	@nOwner int
,	@nStorageType tinyint
,	@nStorage smallint
,	@nRet tinyint OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000

	IF EXISTS(SELECT nItemKey 
				FROM tItem 
			   WHERE nOwner = @nOwner 
				 AND nStorageType = @nStorageType 
				 AND nStorage = @nStorage
				 AND nFlags = 0) BEGIN
		SET @nRet = 0
	END
	ELSE BEGIN
		BEGIN TRAN
		
		UPDATE tItem 
		SET	nOwner = @nOwner, nStorageType = @nStorageType, nStorage = @nStorage
		WHERE nItemKey = @nItemKey
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			SET @nRet = 0
			ROLLBACK TRAN
		END
		ELSE BEGIN
			SET @nRet = 1
			COMMIT TRAN
		END
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SetStorageAndOwner_UseEmptyStorage]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Get item storage
2004.8 By CJC
 input:
	nItemKey	 = Item Key
	nOwner, nStorageType, nStorage = Storage new value
 output:
	1 = OK
	0 = Not found or error
*/
CREATE PROCEDURE [dbo].[p_Item_SetStorageAndOwner_UseEmptyStorage]
	@nItemKey bigint
,	@nOwner int
,	@nStorageType tinyint
,	@nStorage smallint OUTPUT
,	@nRet tinyint OUTPUT
AS
BEGIN
	SET NOCOUNT ON

	-- 빈인벤 위치찾기
	EXEC  p_Item_GetStorageEmpty @nOwner, @nStorageType, @nStorage OUTPUT
	IF @nStorage < 0
	BEGIN
		SET @nRet = -1
		RETURN
	END

	IF EXISTS(SELECT nItemKey 
				FROM tItem 
			   WHERE nOwner = @nOwner 
				 AND nStorageType = @nStorageType 
				 AND nStorage = @nStorage
				 AND nFlags = 0) BEGIN
		SET @nRet = 0
	END
	ELSE BEGIN
		BEGIN TRAN
		
		UPDATE tItem 
		   SET nOwner = @nOwner, nStorageType = @nStorageType, nStorage = @nStorage
		 WHERE nItemKey = @nItemKey
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			SET @nRet = 0
			ROLLBACK TRAN
		END
		ELSE BEGIN
			SET @nRet = 1
			COMMIT TRAN
		END
	END
END


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SetTitle]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_SetTitle]
/*
Item Set Title
2004.8 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nItemKey bigint,
@nTitleType smallint,
@nTitleCharNo int,
@sTitle nvarchar(24),
-- Output var
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tItemTitle SET 
nTitleType = @nTitleType,
nTitleCharNo = @nTitleCharNo,
sTitle = @sTitle
WHERE nItemKey = @nItemKey
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tItemTitle (  nItemKey,  nTitleType,  nTitleCharNo,  sTitle )
	VALUES			  ( @nItemKey, @nTitleType, @nTitleCharNo, @sTitle )
END
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_SetWeaponTitle]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_SetWeaponTitle]
/*
Item Set Weapon Title
2005.8 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        1 = Error Set Weapon mob 
	        2 = Error Set Weapon user
	        3 = Error Delete license item
	        ? = Error DB
*/
@nWeaponItemKey bigint,
@nLicenseItemKey bigint,
@nMobID smallint,
@nTitleCharNo int,
@sTitle nvarchar(24),
-- Output var
@nRet int OUTPUT
AS
SET NOCOUNT ON
BEGIN TRAN
-- 아이템에 몹 라이센스 붙이기
EXEC p_Item_SetMobList @nWeaponItemKey, @nMobID, 0, 0, @nRet OUTPUT
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 1
	RETURN
END
-- 처음 붙은 아이템의 경우 최초 제작자 정보를 세팅한다.
DECLARE @nRetTemp int
SELECT @nRetTemp = COUNT(*) FROM tItemMobList WHERE nItemKey = @nWeaponItemKey
IF @nRetTemp = 1
BEGIN
	EXEC p_Item_SetTitle @nWeaponItemKey, 0, @nTitleCharNo, @sTitle, @nRet OUTPUT
	IF @nRet <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 2
		RETURN
	END
END
-- 사용된 라이센스 아이템은 지운다.
SET @nRetTemp = 1
EXEC p_Item_Delete @nLicenseItemKey, @nRetTemp OUTPUT
IF @nRetTemp <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 3
	RETURN
END
-- 성공
COMMIT TRAN
SET @nRet = 0
RETURN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Split_N_Merge]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_Split_N_Merge]
/*
Item Split and Merge - change lot
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found from item
	        2 = Missmatch from item owner
	        3 = Not found to item
	        4 = Missmatch to item owner
	        ? = Error code(Lot change/Delete item error)
*/
@nItemKeyFrom bigint,
@nOwnerFrom int,
@nOptionTypeFrom smallint,
@nOptionDataFrom bigint,
@nItemKeyTo bigint,
@nOwnerTo int,
@nOptionTypeTo smallint,
@nOptionDataTo bigint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 수량 줄어들 아이템(From) 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKeyFrom, @nOwnerFrom, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END
-- 수량 늘어날 아이템(To) 소유자 확인
EXEC p_Item_IsValidOwner @nItemKeyTo, @nOwnerTo, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet + 2
	RETURN
END
BEGIN TRAN
-- 수량 줄어들 아이템 랏 변경저장프로시져 호출
EXEC p_Item_SetOption @nItemKeyFrom, @nOptionTypeFrom, @nOptionDataFrom, @nRet OUTPUT
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN
	RETURN
END
-- 수량 늘어날 아이템 랏 변경저장프로시져 호출
EXEC p_Item_SetOption @nItemKeyTo, @nOptionTypeTo, @nOptionDataTo, @nRet OUTPUT
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN
	RETURN
END
-- 완료
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Split_N_Merge_New]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_Split_N_Merge_New]
/*
Item Split and Merge - change lot
2004.9 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found from item
	        2 = Missmatch from item owner
	        3 = Not found to item
	        4 = Missmatch to item owner
                     5 = From lot read failed
                     6 = From lot less more nSplitLot
                     7 = To lot read failed
                     8 = From lot set failed
                     9 = To lot set failed
*/
@nItemKeyFrom bigint,
@nOwnerFrom int,
@nOptionTypeFrom smallint,
@nOptionDataFrom bigint OUTPUT,
@nItemKeyTo bigint,
@nOwnerTo int,
@nOptionTypeTo smallint,
@nOptionDataTo bigint OUTPUT,
@nSplitLot bigint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 수량 줄어들 아이템(From) 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKeyFrom, @nOwnerFrom, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END
-- 수량 늘어날 아이템(To) 소유자 확인
EXEC p_Item_IsValidOwner @nItemKeyTo, @nOwnerTo, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet + 2
	RETURN
END
-- 빼질 아이템 랏 얻기
EXEC p_Item_GetOption @nItemKeyFrom, @nOptionTypeFrom, @nOptionDataFrom OUTPUT, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	SET @nRet = 5
	RETURN
END
-- 빼질 아이템 랏이 충분한지 확인
IF @nOptionDataFrom < @nSplitLot
BEGIN
	SET @nRet = 6
	RETURN
END
-- 더해질 아이템 랏 얻기
DECLARE @nOptionDataLotAdd bigint
EXEC p_Item_GetOption @nItemKeyTo, @nOptionTypeTo, @nOptionDataTo OUTPUT, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	SET @nRet = 7
	RETURN
END
-- 결과 랏 계산
SET @nOptionDataFrom = @nOptionDataFrom - @nSplitLot
SET @nOptionDataTo = @nOptionDataTo + @nSplitLot
BEGIN TRAN
-- 수량 줄어들 아이템 랏 변경저장프로시져 호출
EXEC p_Item_SetOption @nItemKeyFrom, @nOptionTypeFrom, @nOptionDataFrom, @nRet OUTPUT
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 8
	RETURN
END
-- 수량 늘어날 아이템 랏 변경저장프로시져 호출
EXEC p_Item_SetOption @nItemKeyTo, @nOptionTypeTo, @nOptionDataTo, @nRet OUTPUT
IF @nRet <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 9
	RETURN
END
-- 완료
COMMIT TRAN
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Upgrade]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_Upgrade]
/*
Item upgrade
2005.6 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Not enough money to sub
	        4 = Upgrade value setting, upgrade fail count error(option set error)
	        5 = Raw delete fail
	        6 = RawLeft delete fail, if valid item
	        7 = RawRight delete fail, if valid item
	        8 = RawMiddle delete fail, if valid item
	        
 operation:
	1. money sub
	2. upgrade item level
	3. delete raws
*/
@nOwner int,
@nItemKey bigint,
@nItemDestroy int,
@nUpgradeOptionType smallint,
@nUpgradeOptionValue bigint,
@nUpgradeFailCountType smallint,
@nUpgradeFailCountValue bigint,
@nRawKey bigint,
@nRawLeftKey bigint,
@nRawRightKey bigint,
@nRawMiddleKey bigint,
@nGiftMoney bigint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 아이템 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKey, @nOwner, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END
-- 아이템 소유자의 돈 감소
BEGIN TRAN
IF @nGiftMoney > 0 -- 수고비가 있는 경우, 금액을 빼준다.
BEGIN
	EXEC p_Char_MoneySub @nOwner, @nGiftMoney, @nTinyintRet OUTPUT
	IF @nTinyintRet <> 1
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 3
		RETURN
	END
END	
-- 아이템 업그레이드 값 조정
DECLARE @nRetTemp int
IF @nItemDestroy = 1 -- 업글 실패로 아이템 파괴해야 되는경우
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nItemKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
END
ELSE
BEGIN
	-- 업글 실패로 파괴가 아닌 경우, 새로운 업글값, 실패 카운트 기록	
	SET @nRetTemp = 1
	EXEC p_Item_SetOption @nItemKey, @nUpgradeOptionType, @nUpgradeOptionValue, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
	
	SET @nRetTemp = 1
	EXEC p_Item_SetOption @nItemKey, @nUpgradeFailCountType, @nUpgradeFailCountValue, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
END
-- 사용된 자원 지우기
SET @nRetTemp = 1
EXEC p_Item_Delete @nRawKey, @nRetTemp OUTPUT
IF @nRetTemp <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 5
	RETURN
END
-- 사용된 자원왼족 지우기(입력된 값이 있으면)
IF @nRawLeftKey <> 0
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nRawLeftKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 6
		RETURN
	END
END
-- 사용된 자원오른쪽 지우기(입력된 값이 있으면)
IF @nRawRightKey <> 0
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nRawRightKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 7
		RETURN
	END
END
-- 사용된 자원가운데 지우기(입력된 값이 있으면)
IF @nRawMiddleKey <> 0
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nRawMiddleKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 8
		RETURN
	END
END
-- 업글 성공
COMMIT TRAN
SET @nRet = 0
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Upgrade_CelllInAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_Upgrade_CelllInAll]
/*
Item upgrade
2008.2 By Lunar
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Not enough money to sub
	        4 = Upgrade value setting, upgrade fail count error(option set error)
	        5 = Raw delete fail
	        6 = RawLeft delete fail, if valid item
	        7 = RawRight delete fail, if valid item
	        8 = RawMiddle delete fail, if valid item
	        
 operation:
	1. money sub
	2. upgrade item level
	3. delete raws
*/
@nOwner int,
@nItemKey bigint,
@nItemDestroy int,
@nUpgradeOptionType smallint,
@nUpgradeOptionValue bigint,
@nUpgradeFailCountType smallint,
@nUpgradeFailCountValue bigint,
@nRawKey bigint,
@nRawLeftKey bigint,
@nRawRightKey bigint,
@nRawMiddleKey bigint,
@nGiftMoney bigint,
@nRawOptionType smallint,
@nRawLot smallint,
@nRawLeftOptionType smallint,
@nRawLeftLot smallint,
@nRawRightOptionType smallint,
@nRawRightLot smallint,
@nRawMiddleOptionType smallint,
@nRawMiddleLot smallint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 아이템 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKey, @nOwner, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END
-- 아이템 소유자의 돈 감소
BEGIN TRAN
IF @nGiftMoney > 0 -- 수고비가 있는 경우, 금액을 빼준다.
BEGIN
	EXEC p_Char_MoneySub @nOwner, @nGiftMoney, @nTinyintRet OUTPUT
	IF @nTinyintRet <> 1
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 3
		RETURN
	END
END	
-- 아이템 업그레이드 값 조정
DECLARE @nRetTemp int
IF @nItemDestroy = 1 -- 업글 실패로 아이템 파괴해야 되는경우
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nItemKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
END
ELSE
BEGIN
	-- 업글 실패로 파괴가 아닌 경우, 새로운 업글값, 실패 카운트 기록	
	SET @nRetTemp = 1
	EXEC p_Item_SetOption @nItemKey, @nUpgradeOptionType, @nUpgradeOptionValue, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
	
	SET @nRetTemp = 1
	EXEC p_Item_SetOption @nItemKey, @nUpgradeFailCountType, @nUpgradeFailCountValue, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
END
-- 사용된 자원 지우기
IF @nRawKey <> 0
BEGIN
	IF @nRawLot = 1
	BEGIN
		SET @nRetTemp = 1
		EXEC p_Item_Delete @nRawKey, @nRetTemp OUTPUT
		IF @nRetTemp <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 5
			RETURN
		END
	END
	IF @nRawLot > 1
	BEGIN
		SET @nRetTemp = 1
		SET @nRawLot = @nRawLot - 1
		EXEC p_Item_SetOption @nRawKey, @nRawOptionType, @nRawLot, @nRetTemp OUTPUT
		IF @nRetTemp <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 5
			RETURN
		END
	END
END
-- 사용된 자원왼족 지우기(입력된 값이 있으면)
IF @nRawLeftKey <> 0
BEGIN
	IF @nRawLeftLot = 1
	BEGIN
		SET @nRetTemp = 1
		EXEC p_Item_Delete @nRawLeftKey, @nRetTemp OUTPUT
		IF @nRetTemp <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 6
			RETURN
		END
	END
	IF @nRawLeftLot > 1
	BEGIN
		SET @nRetTemp = 1
		SET @nRawLeftLot = @nRawLeftLot - 1
		EXEC p_Item_SetOption @nRawLeftKey, @nRawLeftOptionType, @nRawLeftLot, @nRetTemp OUTPUT
		IF @nRetTemp <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 6
			RETURN
		END
	END
END
-- 사용된 자원오른쪽 지우기(입력된 값이 있으면)
IF @nRawRightKey <> 0
BEGIN
	IF @nRawRightLot = 1
	BEGIN
		SET @nRetTemp = 1
		EXEC p_Item_Delete @nRawRightKey, @nRetTemp OUTPUT
		IF @nRetTemp <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 7
			RETURN
		END
	END
	IF @nRawRightLot > 1
	BEGIN
		SET @nRetTemp = 1
		SET @nRawRightLot = @nRawRightLot - 1
		EXEC p_Item_SetOption @nRawRightKey, @nRawRightOptionType, @nRawRightLot, @nRetTemp OUTPUT
		IF @nRetTemp <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 7
			RETURN
		END
	END
END
-- 사용된 자원가운데 지우기(입력된 값이 있으면)
IF @nRawMiddleKey <> 0
BEGIN
	IF @nRawMiddleLot = 1
	BEGIN
		SET @nRetTemp = 1
		EXEC p_Item_Delete @nRawMiddleKey, @nRetTemp OUTPUT
		IF @nRetTemp <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 8
			RETURN
		END
	END
	IF @nRawMiddleLot > 1
	BEGIN
		SET @nRetTemp = 1
		SET @nRawMiddleLot = @nRawMiddleLot - 1
		EXEC p_Item_SetOption @nRawMiddleKey, @nRawMiddleOptionType, @nRawMiddleLot, @nRetTemp OUTPUT
		IF @nRetTemp <> 0
		BEGIN
			ROLLBACK TRAN
			SET @nRet = 8
			RETURN
		END
	END
END
-- 업글 성공
COMMIT TRAN
SET @nRet = 0
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Upgrade_GOLD_NINE]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_Upgrade_GOLD_NINE]
/*
Item upgrade
2005.6 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Not enough money to sub
	        4 = Upgrade value setting, upgrade fail count error(option set error)
	        5 = Raw delete fail
	        6 = RawLeft delete fail, if valid item
	        7 = RawRight delete fail, if valid item
	        8 = RawMiddle delete fail, if valid item
	        
 operation:
	1. money sub
	2. upgrade item level
	3. delete raws
*/
@nOwner int,
@nItemKey bigint,
@nItemDestroy int,
@nUpgradeOptionType smallint,
@nUpgradeOptionValue bigint,
@nUpgradeFailCountType smallint,
@nUpgradeFailCountValue bigint,
@nRawKey bigint,
@nRawLeftKey bigint,
@nRawRightKey bigint,
@nRawMiddleKey bigint,
@nGiftMoney bigint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 아이템 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKey, @nOwner, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END
-- 아이템 소유자의 돈 감소
BEGIN TRAN
IF @nGiftMoney > 0 -- 수고비가 있는 경우, 금액을 빼준다.
BEGIN
	EXEC p_Char_MoneySub @nOwner, @nGiftMoney, @nTinyintRet OUTPUT
	IF @nTinyintRet <> 1
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 3
		RETURN
	END
END	
-- 아이템 업그레이드 값 조정
DECLARE @nRetTemp int
IF @nItemDestroy = 1 -- 업글 실패로 아이템 파괴해야 되는경우
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nItemKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
END
ELSE
BEGIN
	-- 업글 실패로 파괴가 아닌 경우, 새로운 업글값, 실패 카운트 기록	
	SET @nRetTemp = 1
	EXEC p_Item_SetOption @nItemKey, @nUpgradeOptionType, @nUpgradeOptionValue, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
	
	SET @nRetTemp = 1
	EXEC p_Item_SetOption @nItemKey, @nUpgradeFailCountType, @nUpgradeFailCountValue, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
END
-- 사용된 자원 지우기
SET @nRetTemp = 1
EXEC p_Item_Delete @nRawKey, @nRetTemp OUTPUT
IF @nRetTemp <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 5
	RETURN
END
-- 사용된 자원왼족 지우기(입력된 값이 있으면)
IF @nRawLeftKey <> 0
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nRawLeftKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 6
		RETURN
	END
END
-- 사용된 자원오른쪽 지우기(입력된 값이 있으면)
IF @nRawRightKey <> 0
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nRawRightKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 7
		RETURN
	END
END
-- 사용된 자원가운데 지우기(입력된 값이 있으면)
IF @nRawMiddleKey <> 0
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nRawMiddleKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 8
		RETURN
	END
END
-- 업글 성공
COMMIT TRAN
SET @nRet = 0
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Item_Upgrade_OLD]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Item_Upgrade_OLD]
/*
Item upgrade
2005.6 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Not found item
	        2 = Missmatch item owner
	        3 = Not enough money to sub
	        4 = Upgrade value setting, upgrade fail count error(option set error)
	        5 = Raw delete fail
	        6 = RawLeft delete fail, if valid item
	        7 = RawRight delete fail, if valid item
	        
 operation:
	1. money sub
	2. upgrade item level
	3. delete raws
*/
@nOwner int,
@nItemKey bigint,
@nItemDestroy int,
@nUpgradeOptionType smallint,
@nUpgradeOptionValue bigint,
@nUpgradeFailCountType smallint,
@nUpgradeFailCountValue bigint,
@nRawKey bigint,
@nRawLeftKey bigint,
@nRawRightKey bigint,
@nGiftMoney bigint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 아이템 소유자 확인
DECLARE @nTinyintRet tinyint
EXEC p_Item_IsValidOwner @nItemKey, @nOwner, @nTinyintRet OUTPUT
IF @nTinyintRet <> 0
BEGIN
	SET @nRet = @nTinyintRet
	RETURN
END
-- 아이템 소유자의 돈 감소
BEGIN TRAN
IF @nGiftMoney > 0 -- 수고비가 있는 경우, 금액을 빼준다.
BEGIN
	EXEC p_Char_MoneySub @nOwner, @nGiftMoney, @nTinyintRet OUTPUT
	IF @nTinyintRet <> 1
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 3
		RETURN
	END
END	
-- 아이템 업그레이드 값 조정
DECLARE @nRetTemp int
IF @nItemDestroy = 1 -- 업글 실패로 아이템 파괴해야 되는경우
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nItemKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
END
ELSE
BEGIN
	-- 업글 실패로 파괴가 아닌 경우, 새로운 업글값, 실패 카운트 기록	
	SET @nRetTemp = 1
	EXEC p_Item_SetOption @nItemKey, @nUpgradeOptionType, @nUpgradeOptionValue, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
	
	SET @nRetTemp = 1
	EXEC p_Item_SetOption @nItemKey, @nUpgradeFailCountType, @nUpgradeFailCountValue, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 4
		RETURN
	END
END
-- 사용된 자원 지우기
SET @nRetTemp = 1
EXEC p_Item_Delete @nRawKey, @nRetTemp OUTPUT
IF @nRetTemp <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 5
	RETURN
END
-- 사용된 자원왼족 지우기(입력된 값이 있으면)
IF @nRawLeftKey <> 0
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nRawLeftKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 6
		RETURN
	END
END
-- 사용된 자원오른쪽 지우기(입력된 값이 있으면)
IF @nRawRightKey <> 0
BEGIN
	SET @nRetTemp = 1
	EXEC p_Item_Delete @nRawRightKey, @nRetTemp OUTPUT
	IF @nRetTemp <> 0
	BEGIN
		ROLLBACK TRAN
		SET @nRet = 7
		RETURN
	END
END
-- 업글 성공
COMMIT TRAN
SET @nRet = 0
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_MiniHouseURL_Get]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_MiniHouseURL_Get]
	@nUserNo int,
	@sURL NVARCHAR(255) output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000
	EXEC Account.dbo.usp_MiniHouseURL_GET @nUserNo, @sURL OUTPUT
	
	SET NOCOUNT OFF
	SET LOCK_TIMEOUT -1
END


GO
/****** Object:  StoredProcedure [dbo].[p_MiniHouseURL_Set]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_MiniHouseURL_Set]
	@nUserNo int,
	@sURL NVARCHAR(255)
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000
	EXEC Account.dbo.usp_MiniHouseURL_GET @nUserNo, @sURL
	
	SET NOCOUNT OFF
	SET LOCK_TIMEOUT -1
END


GO
/****** Object:  StoredProcedure [dbo].[p_Prison_Add]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-03-14
@return	0		<성공>
	others		<실패>
@brief	강금한다.
==================================================*/
CREATE PROCEDURE [dbo].[p_Prison_Add] 
@sGmUserID nvarchar(16),
@sImprison nvarchar(16),
@nMinute smallint,
@sReason nvarchar(16), 
@sRemark nvarchar(64),
@nImprisonRegNum int,
@err smallint OUTPUT
AS
SET NOCOUNT ON
DECLARE	
@nRet		int,
@nPrisonMin 	int
SET 		@err = 0
BEGIN TRAN
UPDATE tCharacter SET 
	nPrisonMin=@nMinute ,
	nLoginZoneX=896,
	nLoginZoneY=1122,
	sLoginZone='EldPri' 	
	WHERE nCharNo=@nImprisonRegNum
IF @@error <> 0 GOTO ERR
INSERT tPrison (nCharID,nMinute,sReason,sGmID,sRemark)
VALUES (@nImprisonRegNum,@nMinute,@sReason,@sGmUserID,@sRemark )
IF @@error <> 0 GOTO ERR
COMMIT TRAN
RETURN @@error
ERR:
ROLLBACK TRAN
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Prison_Add_v2]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-03-14
@return	0		<성공>
	others		<실패>
@brief	강금한다.
==================================================*/
CREATE PROCEDURE [dbo].[p_Prison_Add_v2] 
@sGmUserID nvarchar(16),
@sImprison nvarchar(16),
@nMinute smallint,
@sReason nvarchar(16), 
@sRemark nvarchar(64),
@nImprisonRegNum int,
@sRegenMapName varchar(16),
@nRegenX int,
@nRegenY int,
@err smallint OUTPUT
AS
SET NOCOUNT ON
DECLARE	
@nRet		int,
@nPrisonMin 	int
SET 		@err = 0
BEGIN TRAN
UPDATE tCharacter SET 
	nPrisonMin=@nMinute ,
	nLoginZoneX=896,
	nLoginZoneY=1122,
	sLoginZone='EldPri' 	
	WHERE nCharNo=@nImprisonRegNum
IF @@error <> 0 GOTO ERR
INSERT tPrison (nCharID,nMinute,sReason,sGmID,sRemark,sRegenMapName,nRegenX,nRegenY)
VALUES (@nImprisonRegNum,@nMinute,@sReason,@sGmUserID,@sRemark,@sRegenMapName,@nRegenX,@nRegenY )
IF @@error <> 0 GOTO ERR
COMMIT TRAN
RETURN @@error
ERR:
ROLLBACK TRAN
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Prison_Add2]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-03-14
@return	0		<성공>
	others		<실패>
@brief	강금한다.
	케릭터이름으로 강금한다.(오프라인인 사람 강금)
	MapInfo 파일에서 EldPri 부분 수정시 반드시 프로시져 수정해야함.
	nLoginZoneX=896,
	nLoginZoneY=1122,
	sLoginZone='EldPri' 
==================================================*/
CREATE PROCEDURE [dbo].[p_Prison_Add2]
@sGmUserID nvarchar(16),
@sImprison nvarchar(16),
@nMinute smallint,
@sReason nvarchar(16), 
@sRemark nvarchar(64),
@err smallint OUTPUT
AS
SET NOCOUNT ON
DECLARE	
@nRet		int,
@nPrisonMin 	int,
@nImprisonRegNum int 
SET 		@err = 0
	--케릭터ID가 존재하지 않습니다.
SELECT @nImprisonRegNum=nCharNo, @nPrisonMin=nPrisonMin FROM tCharacter(NOLOCK) WHERE sID=@sImprison 
IF @@ROWCOUNT = 0
BEGIN
	SET @err = 1
	RETURN @@error
END
	--이미 수감중입니다
IF @nPrisonMin <> 0
BEGIN
	SET @err = 2
	RETURN @@error
END
BEGIN TRAN
UPDATE tCharacter SET
 	nPrisonMin=@nMinute, 
	nLoginZoneX=896,
	nLoginZoneY=1122,
	sLoginZone='EldPri' 		
	WHERE nCharNo=@nImprisonRegNum
IF @@error <> 0 GOTO ERR
INSERT tPrison (nCharID,nMinute,sReason,sGmID,sRemark)
VALUES (@nImprisonRegNum,@nMinute,@sReason,@sGmUserID,@sRemark )
IF @@error <> 0 GOTO ERR
COMMIT TRAN
RETURN @@error
ERR:
ROLLBACK TRAN
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Prison_Add2_v2]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-03-14
@return	0		<성공>
	others		<실패>
@brief	강금한다.
	케릭터이름으로 강금한다.(오프라인인 사람 강금)
	MapInfo 파일에서 EldPri 부분 수정시 반드시 프로시져 수정해야함.
	nLoginZoneX=896,
	nLoginZoneY=1122,
	sLoginZone='EldPri' 
==================================================*/
CREATE PROCEDURE [dbo].[p_Prison_Add2_v2]
@sGmUserID nvarchar(16),
@sImprison nvarchar(16),
@nMinute smallint,
@sReason nvarchar(16), 
@sRemark nvarchar(64),
@sRegenMapName varchar(16),
@nRegenX int,
@nRegenY int,
@err smallint OUTPUT
AS
SET NOCOUNT ON
DECLARE	
@nRet		int,
@nPrisonMin 	int,
@nImprisonRegNum int 
SET 		@err = 0
	--케릭터ID가 존재하지 않습니다.
SELECT @nImprisonRegNum=nCharNo, @nPrisonMin=nPrisonMin FROM tCharacter(NOLOCK) WHERE sID=@sImprison 
IF @@ROWCOUNT = 0
BEGIN
	SET @err = 1
	RETURN @@error
END
	--이미 수감중입니다
IF @nPrisonMin <> 0
BEGIN
	SET @err = 2
	RETURN @@error
END
BEGIN TRAN
UPDATE tCharacter SET
 	nPrisonMin=@nMinute, 
	nLoginZoneX=896,
	nLoginZoneY=1122,
	sLoginZone='EldPri' 		
	WHERE nCharNo=@nImprisonRegNum
IF @@error <> 0 GOTO ERR
INSERT tPrison (nCharID,nMinute,sReason,sGmID,sRemark,sRegenMapName,nRegenX,nRegenY)
VALUES (@nImprisonRegNum,@nMinute,@sReason,@sGmUserID,@sRemark,@sRegenMapName,@nRegenX,@nRegenY )
IF @@error <> 0 GOTO ERR
COMMIT TRAN
RETURN @@error
ERR:
ROLLBACK TRAN
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Prison_Alter]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-03-14
@return	0		<성공>
	others		<실패>
@brief	강금변경한다.
==================================================*/
CREATE PROCEDURE [dbo].[p_Prison_Alter] 
@sGmUserID nvarchar(16),
@sImprison nvarchar(16),
@nMinute smallint,
@sReason nvarchar(16), 
@sRemark nvarchar(64),
@nImprisonRegNum int,
@err smallint OUTPUT
AS
SET NOCOUNT ON
DECLARE	
@nRet		int,
@nPrisonMin 	int
SET 		@err = 0
BEGIN TRAN
IF @nMinute = 0
	BEGIN
		UPDATE tCharacter SET
 		nPrisonMin=@nMinute, 
		nLoginZoneX=5963,
		nLoginZoneY=9793,
		sLoginZone='Rou' 		
		WHERE nCharNo=@nImprisonRegNum
	END
ELSE
	BEGIN
		UPDATE tCharacter SET
 		nPrisonMin=@nMinute, 
		nLoginZoneX=896,
		nLoginZoneY=1122,
		sLoginZone='EldPri' 		
		WHERE nCharNo=@nImprisonRegNum
	END
IF @@error <> 0 GOTO ERR
INSERT tPrison (nCharID,nMinute,sReason,sGmID,sRemark)
VALUES (@nImprisonRegNum,@nMinute,@sReason,@sGmUserID,@sRemark )
IF @@error <> 0 GOTO ERR
COMMIT TRAN
RETURN @@error
ERR:
ROLLBACK TRAN
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Prison_Alter2]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-03-14
@return	0		<성공>
	others		<실패>
@brief	강금변경한다.
	케릭터이름으로 강금변경한다.(오프라인인 사람 강금변경)
	MapInfo 파일에서 EldPri 부분 수정시 반드시 프로시져 수정해야함.
	nLoginZoneX=896,
	nLoginZoneY=1122,
	sLoginZone='EldPri' 
==================================================*/
CREATE PROCEDURE [dbo].[p_Prison_Alter2]
@sGmUserID nvarchar(16),
@sImprison nvarchar(16),
@nMinute smallint,
@sReason nvarchar(16), 
@sRemark nvarchar(64),
@err smallint OUTPUT
AS
SET NOCOUNT ON
DECLARE	
@nRet		int,
@nPrisonMin 	int,
@nImprisonRegNum int 
SET 		@err = 0
	--케릭터ID가 존재하지 않습니다.
SELECT @nImprisonRegNum=nCharNo, @nPrisonMin=nPrisonMin FROM tCharacter(NOLOCK) WHERE sID=@sImprison 
IF @@ROWCOUNT = 0
BEGIN
	SET @err = 1
	RETURN @@error
END
--수감중이 아닐때...
IF @nPrisonMin = 0
BEGIN
	SET @err = 2
	RETURN @@error
END
BEGIN TRAN
IF @nMinute = 0
	BEGIN
		UPDATE tCharacter SET
 		nPrisonMin=@nMinute, 
		nLoginZoneX=5963,
		nLoginZoneY=9793,
		sLoginZone='Rou' 		
		WHERE nCharNo=@nImprisonRegNum
	END
ELSE
	BEGIN
		UPDATE tCharacter SET
 		nPrisonMin=@nMinute, 
		nLoginZoneX=896,
		nLoginZoneY=1122,
		sLoginZone='EldPri' 		
		WHERE nCharNo=@nImprisonRegNum
	END
IF @@error <> 0 GOTO ERR
INSERT tPrison (nCharID,nMinute,sReason,sGmID,sRemark)
VALUES (@nImprisonRegNum,@nMinute,@sReason,@sGmUserID,@sRemark )
IF @@error <> 0 GOTO ERR
COMMIT TRAN
RETURN @@error
ERR:
ROLLBACK TRAN
return @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Prison_End]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-03-18
@return	0		<성공>
	others		<실패>
@brief	출소한다.
==================================================*/
CREATE PROCEDURE [dbo].[p_Prison_End] 
@nImprisonRegNum	int
AS
SET NOCOUNT ON
UPDATE tCharacter SET 	nLoginZoneX=5963, 
			nLoginZoneY=9793, 
			nLoginZoneD=90,
			sLoginZone='Rou', 
			nPrisonMin=0 
	WHERE nCharNo=@nImprisonRegNum
RETURN @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Prison_Get]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-03-22
@return	0		<성공>
	others		<실패>
@brief	감금정보를 얻는다.
	tCharacter 테이블에 nPrisonNum필드를 넣어줘야 정확하지만
	최소한의 수정을 위해서 일단 Top을 사용함.
==================================================*/
CREATE PROCEDURE [dbo].[p_Prison_Get] 
@nCharID	int
AS
SET NOCOUNT ON
SELECT TOP 1 sReason, sRemark FROM tPrison
WHERE nCharID = @nCharID 
ORDER BY dPrisonDate DESC
RETURN @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Prison_Get_v2]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-03-22
@return	0		<성공>
	others		<실패>
@brief	감금정보를 얻는다.
	tCharacter 테이블에 nPrisonNum필드를 넣어줘야 정확하지만
	최소한의 수정을 위해서 일단 Top을 사용함.
==================================================*/
CREATE PROCEDURE [dbo].[p_Prison_Get_v2] 
@nCharID	int
AS
SET NOCOUNT ON
SELECT TOP 1 sReason, sRemark, sRegenMapName, nRegenX, nRegenY FROM tPrison
WHERE nCharID = @nCharID 
ORDER BY dPrisonDate DESC
RETURN @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Prison_UpdateCharPrisonMin]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*==================================================
@author	lenasoft
@date	2006-03-14
@return	0		<성공>
	others		<실패>
@brief	강금시간 업데이트한다.
==================================================*/
CREATE PROCEDURE [dbo].[p_Prison_UpdateCharPrisonMin] 
@nImprisonRegNum	int, 
@nMinute		smallint
AS
SET NOCOUNT ON
--감옥시간과 로긴존과의 동기화를 위해서 꼭!!! 같이 업데이트 해줘야함.
IF @nMinute = 0
	BEGIN
		UPDATE tCharacter SET
 		nPrisonMin=@nMinute, 
		nLoginZoneX=5963,
		nLoginZoneY=9793,
		sLoginZone='Rou' 		
		WHERE nCharNo=@nImprisonRegNum
	END
ELSE
	BEGIN
		UPDATE tCharacter SET
 		nPrisonMin=@nMinute, 
		sLoginZone='EldPri' 		
		WHERE nCharNo=@nImprisonRegNum
	END
RETURN @@error


GO
/****** Object:  StoredProcedure [dbo].[p_Quest_Add]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Quest_Add]
/*
Quest Set
2004.10 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nQuestNo int,
@nStatus tinyint,
@sData varbinary(100),
@nRet int OUTPUT
AS
SET NOCOUNT ON
INSERT tQuest (  nCharNo,  nQuestNo,  nStatus,  sData )
VALUES        ( @nCharNo, @nQuestNo, @nStatus, @sData )
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Quest_Del]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Quest_Del]
/*
Quest Delete
2004.10 By CJC
 input:
	nCharNo, nQuestNo = To be delete info.
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nQuestNo int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
DELETE FROM tQuest WHERE nCharNo = @nCharNo AND nQuestNo = @nQuestNo
IF (@@ERROR=0) AND (@@ROWCOUNT=1)
	SET @nRet = 0
ELSE
	SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Quest_Get]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Quest_Get]
/*
Quest Get
2004.10 By CJC
 input:
	see SQL
 output:
	@nRet	0 = No data found
	        ? = Number data here(must to be 1)
*/
@nCharNo int,
@nQuestNo int,
@nStatus tinyint OUTPUT,
@sData varbinary(100) OUTPUT,
@nRet int OUTPUT
AS
SET NOCOUNT ON
SELECT 
	@nStatus = nStatus, 
	@sData = sData
FROM tQuest WHERE nCharNo = @nCharNo AND nQuestNo = @nQuestNo
SET @nRet = @@ROWCOUNT
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Quest_GetAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Quest_GetAll]
/*
Quest Get All
2004.10 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int
AS
SET NOCOUNT ON
SELECT nQuestNo, nStatus, sData FROM tQuest WHERE nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Quest_GetAllDoing]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Quest_GetAllDoing]
/*
Quest Get All
2004.10 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int,
@nStatusDone tinyint
AS
SET NOCOUNT ON
SELECT nQuestNo, nStatus, sData FROM tQuest WHERE nCharNo = @nCharNo AND nStatus = @nStatusDone
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Quest_GetAllDone]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Quest_GetAllDone]
/*
Quest Get All
2004.10 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int,
@nStatusDone tinyint
AS
SET NOCOUNT ON
SELECT nQuestNo FROM tQuest WHERE nCharNo = @nCharNo AND nStatus = @nStatusDone
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Quest_Set]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Quest_Set]
/*
Quest Set
2004.10 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nQuestNo int,
@nStatus tinyint,
@sData varbinary(100),
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tQuest SET 
    nStatus = @nStatus,
	sData = @sData
WHERE nCharNo = @nCharNo AND nQuestNo = @nQuestNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tQuest (  nCharNo,  nQuestNo,  nStatus,  sData )
	VALUES        ( @nCharNo, @nQuestNo, @nStatus, @sData )
END
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Skill_Del]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Skill_Del]
/*
Skill Delete
2004.10 By CJC
 input:
	nCharNo, nSkillNo = To be delete info.
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nSkillNo smallint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- 아이템 삭제 옵션
DELETE FROM tSkill WHERE nCharNo = @nCharNo AND nSkillNo = @nSkillNo
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Skill_Get]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Skill_Get]
/*
Skill Get
2004.10 By CJC
 input:
	see SQL
 output:
	@nRet	0 = No data found
	        ? = Number data here(must to be 1)
*/
@nCharNo int,
@nSkillNo smallint,
@nSkillLevel tinyint OUTPUT,
@nSkillExp int OUTPUT,
@nSkillWriteTime bigint OUTPUT,
@nSkillCoolTime int OUTPUT,
@nSkillPowerDemage tinyint OUTPUT,
@nSkillPowerSP tinyint OUTPUT,
@nSkillPowerKeepTime tinyint OUTPUT,
@nSkillPowerCoolTime tinyint OUTPUT,
@nRet int OUTPUT
AS
SET NOCOUNT ON

IF EXISTS(SELECT nCharNo FROM tSkill WHERE nCharNo = @nCharNo AND nSkillNo = @nSkillNo)
BEGIN
	SELECT 
		@nSkillLevel		= nSkillLevel,
		@nSkillExp			= nSkillExp,
		@nSkillWriteTime	= nSkillWriteTime,
		@nSkillCoolTime		= nSkillCoolTime,
		@nSkillPowerDemage	= nSkillPowerDemage,
		@nSkillPowerSP		= nSkillPowerSP,
		@nSkillPowerKeepTime = nSkillPowerKeepTime,
		@nSkillPowerCoolTime = nSkillPowerCoolTime
	FROM tSkill WHERE nCharNo = @nCharNo AND nSkillNo = @nSkillNo
	SET @nRet = @@ROWCOUNT
END
ELSE
BEGIN
	SET	@nSkillLevel		= 0
	SET	@nSkillExp			= 0
	SET	@nSkillWriteTime	= 0
	SET	@nSkillCoolTime		= 0
	SET	@nSkillPowerDemage	= 0
	SET	@nSkillPowerSP		= 0
	SET	@nSkillPowerKeepTime = 0
	SET	@nSkillPowerCoolTime = 0
	SET @nRet = 0
END
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Skill_GetAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Skill_GetAll]
/*
Skill Get All
2004.10 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int
AS
SET NOCOUNT ON
SELECT	nSkillNo, nSkillLevel, nSkillExp, nSkillWriteTime, nSkillCoolTime, 
		nSkillPowerDemage, nSkillPowerSP, nSkillPowerKeepTime, nSkillPowerCoolTime
FROM tSkill WHERE nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Skill_GetNumOfSkill]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Skill_GetNumOfSkill]
/*
Skill Get Num of skill
2005.5 By CJC
 input:
	see SQL
 output:
	fetch to take data
*/
@nCharNo int,
@nNumOfSkill int OUTPUT
AS
SET NOCOUNT ON
SET @nNumOfSkill = 0
SELECT @nNumOfSkill = COUNT(*) FROM tSkill WHERE nCharNo = @nCharNo
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Skill_ResetPower]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Skill_ResetPower]
/*
Skill Reset Power
2005.6 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK, 
	        0 = Error
*/
@nCharNo int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
DECLARE @nFlagsTemp AS int
SET @nRet = 0 -- set error first
SELECT @nFlagsTemp = nFlags FROM tCharacter WHERE nCharNo = @nCharNo
IF @@ROWCOUNT = 0
	RETURN
BEGIN TRAN
SET @nFlagsTemp = @nFlagsTemp & 0x7fffffff -- Clear skillempower_can_reset's Bit
UPDATE tCharacter SET nFlags = @nFlagsTemp WHERE nCharNo = @nCharNo
UPDATE tSkill SET 
	nSkillPowerDemage	= 0,
	nSkillPowerSP		= 0,
	nSkillPowerKeepTime = 0,
	nSkillPowerCoolTime = 0
WHERE nCharNo = @nCharNo
IF @@ERROR <> 0
BEGIN
	ROLLBACK TRAN
	RETURN
END
COMMIT TRAN
SET @nRet = 1 -- no error return
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Skill_Set]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Skill_Set]
/*
Skill Set
2004.10 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nSkillNo smallint,
@nSkillLevel tinyint,
@nSkillExp int,
@nSkillWriteTime bigint,
@nSkillCoolTime int,
@nSkillPowerDemage tinyint,
@nSkillPowerSP tinyint,
@nSkillPowerKeepTime tinyint,
@nSkillPowerCoolTime tinyint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tSkill SET
	nSkillLevel			= @nSkillLevel,
	nSkillExp			= @nSkillExp,
	nSkillWriteTime		= @nSkillWriteTime,
	nSkillCoolTime		= @nSkillCoolTime,
	nSkillPowerDemage	= @nSkillPowerDemage,
	nSkillPowerSP		= @nSkillPowerSP,
	nSkillPowerKeepTime = @nSkillPowerKeepTime,
	nSkillPowerCoolTime = @nSkillPowerCoolTime
WHERE nCharNo = @nCharNo AND nSkillNo = @nSkillNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
BEGIN
	INSERT tSkill (  nCharNo,  nSkillNo,  nSkillLevel,  nSkillExp,  nSkillWriteTime,  nSkillCoolTime,  nSkillPowerDemage,  nSkillPowerSP,  nSkillPowerKeepTime,  nSkillPowerCoolTime )
	VALUES        ( @nCharNo, @nSkillNo, @nSkillLevel, @nSkillExp, @nSkillWriteTime, @nSkillCoolTime, @nSkillPowerDemage, @nSkillPowerSP, @nSkillPowerKeepTime, @nSkillPowerCoolTime )
END
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Skill_SetCoolTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Skill_SetCoolTime]
/*
Skill Set Cool Time
2004.10 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK, 
	        0 = Error
*/
@nCharNo int,
@nSkillNo smallint,
@nSkillWriteTime bigint,
@nSkillCoolTime int,
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tSkill SET
	nSkillWriteTime = @nSkillWriteTime,
	nSkillCoolTime	= @nSkillCoolTime
WHERE nCharNo = @nCharNo AND nSkillNo = @nSkillNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
	SET @nRet = 0
ELSE
	SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Skill_SetPassive]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Skill_SetPassive]
/*
Skill Set Passive
2005.6 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK, 
	        ? = Error code
*/
@nCharNo int,
@nSkillNewNo smallint,
@bSkillOld tinyint,
@nSkillOldNo smallint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
IF @bSkillOld = 1
BEGIN
	UPDATE tSkill 
	SET nSkillNo = @nSkillNewNo
	WHERE nCharNo = @nCharNo AND nSkillNo = @nSkillOldNo
	
	IF @@ERROR <> 0 OR @@ROWCOUNT = 0
		SET @nRet = 1 -- ERROR, No existed old skill
	ELSE
		SET @nRet = 0
		
	RETURN
END
INSERT tSkill (  nCharNo,     nSkillNo )
VALUES        ( @nCharNo, @nSkillNewNo )
SET @nRet = @@ERROR
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Skill_SetPower]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Skill_SetPower]
/*
Skill Set Power
2005.6 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK, 
	        0 = Error
*/
@nCharNo int,
@nSkillNo smallint,
@nSkillPowerSlot tinyint,
@nSkillPowerValue tinyint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
-- nSkillPowerDemage
IF @nSkillPowerSlot = 0
BEGIN
	UPDATE tSkill SET nSkillPowerDemage = @nSkillPowerValue WHERE nCharNo = @nCharNo AND nSkillNo = @nSkillNo
	IF @@ERROR <> 0 OR @@ROWCOUNT = 0
		SET @nRet = 0
	ELSE
		SET @nRet = 1
	RETURN
END
-- nSkillPowerSP
IF @nSkillPowerSlot = 1
BEGIN
	UPDATE tSkill SET nSkillPowerSP = @nSkillPowerValue WHERE nCharNo = @nCharNo AND nSkillNo = @nSkillNo
	IF @@ERROR <> 0 OR @@ROWCOUNT = 0
		SET @nRet = 0
	ELSE
		SET @nRet = 1
	RETURN
END
-- nSkillPowerKeepTime
IF @nSkillPowerSlot = 2
BEGIN
	UPDATE tSkill SET nSkillPowerKeepTime = @nSkillPowerValue WHERE nCharNo = @nCharNo AND nSkillNo = @nSkillNo
	IF @@ERROR <> 0 OR @@ROWCOUNT = 0
		SET @nRet = 0
	ELSE
		SET @nRet = 1
	RETURN
END
-- nSkillPowerCoolTime
IF @nSkillPowerSlot = 3
BEGIN
	UPDATE tSkill SET nSkillPowerCoolTime = @nSkillPowerValue WHERE nCharNo = @nCharNo AND nSkillNo = @nSkillNo
	IF @@ERROR <> 0 OR @@ROWCOUNT = 0
		SET @nRet = 0
	ELSE
		SET @nRet = 1
	RETURN
END
-- ERROR
SET @nRet = 0;
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_Skill_SetPowerAll]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_Skill_SetPowerAll]
/*
Skill Set Power All
2005.6 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK, 
	        0 = Error
*/
@nCharNo int,
@nSkillNo smallint,
@nSkillPowerDemage tinyint,
@nSkillPowerSP tinyint,
@nSkillPowerKeepTime tinyint,
@nSkillPowerCoolTime tinyint,
@nRet int OUTPUT
AS
SET NOCOUNT ON
UPDATE tSkill SET 
	nSkillPowerDemage	= @nSkillPowerDemage,
	nSkillPowerSP		= @nSkillPowerSP,
	nSkillPowerKeepTime	= @nSkillPowerKeepTime,
	nSkillPowerCoolTime	= @nSkillPowerCoolTime
WHERE nCharNo = @nCharNo AND nSkillNo = @nSkillNo
IF @@ERROR <> 0 OR @@ROWCOUNT = 0
	SET @nRet = 0
ELSE
	SET @nRet = 1
-- end


GO
/****** Object:  StoredProcedure [dbo].[p_User_Deposit]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_User_Deposit]
/*
Set User deposit money
2006.5 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Miss match UserNo and User's CharNo
	        2 = Char Money Sub Failed(Not enough money)
	        3 = Add deposit money faield
	        4 = Get result money faield
*/
@nUserNo int,
@nCharNo int,
@nMoney bigint,
@nResultUserMoney bigint OUTPUT,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
SET @nRet = 0
-- Check UserNo and User's CharNo
DECLARE @nDBUserNo int
SET @nDBUserNo = 0
SELECT @nDBUserNo = nUserNo FROM tCharacter WHERE nCharNo = @nCharNo
IF @nDBUserNo <> @nUserNo
BEGIN
	SET @nRet = 1
	RETURN
END
-- Deposit money
BEGIN TRAN
EXEC p_Char_MoneySub @nCharNo, @nMoney, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	SET @nRet = 2
	ROLLBACK TRAN
	RETURN
END
EXEC p_User_MoneyAdd @nUserNo, @nMoney, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	SET @nRet = 3
	ROLLBACK TRAN
	RETURN
END
EXEC p_User_MoneyGet @nUserNo, @nResultUserMoney OUTPUT, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	SET @nRet = 4
	ROLLBACK TRAN
	RETURN
END
-- Done
COMMIT TRAN
SET @nRet = 0
RETURN


GO
/****** Object:  StoredProcedure [dbo].[p_User_MoneyAdd]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_User_MoneyAdd]
/*
Add user money
2005.5 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK
	        0 = Error
*/
@nUserNo int,
@nAddMoney bigint,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
IF @nAddMoney < 0
BEGIN
	SET @nRet = 0
	RETURN
END
DECLARE @nUserMoney bigint
EXEC p_User_MoneyGet @nUserNo, @nUserMoney OUTPUT, @nRet OUTPUT
IF @nRet = 0
	RETURN
-- Add money
SET @nUserMoney = @nUserMoney + @nAddMoney
EXEC p_User_MoneySet @nUserNo, @nUserMoney, @nRet OUTPUT
-- End


GO
/****** Object:  StoredProcedure [dbo].[p_User_MoneyGet]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_User_MoneyGet]
/*
Get user money
2005.5 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK, Money return
	        0 = Error
*/
@nUserNo int,
@nUserMoney bigint OUTPUT,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
SET @nRet = 0
-- 돈 얻기
IF EXISTS(SELECT nUserMoney FROM tUserMoney WHERE nUserNo = @nUserNo )
BEGIN
	SELECT @nUserMoney = nUserMoney FROM tUserMoney WHERE nUserNo = @nUserNo
	IF @@ROWCOUNT = 1
		SET @nRet = 1
	RETURN 
END
-- First access
SET @nUserMoney = 0
INSERT INTO tUserMoney VALUES (@nUserNo, @nUserMoney)
IF @@ROWCOUNT = 1 AND @@ERROR = 0
	SET @nRet = 1
	
RETURN 
-- End


GO
/****** Object:  StoredProcedure [dbo].[p_User_MoneyGetGreaterThen]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
-----------------------------------
SadPig : 2006.9.5 (OPTool)
	Input Parameter
		@nMoney : Money
	Output Parameter
		int nUserNo;
		__int64 nUserMoney;
-----------------------------------
*/
CREATE PROCEDURE [dbo].[p_User_MoneyGetGreaterThen]
	@nMoney		bigint
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000
	SELECT nUserNo, nUserMoney FROM tUserMoney WHERE nUserMoney >=  @nMoney
	
	SET LOCK_TIMEOUT -1
	SET NOCOUNT OFF	
END


GO
/****** Object:  StoredProcedure [dbo].[p_User_MoneySet]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_User_MoneySet]
/*
Set user money
2006.5 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK
	        0 = Error
*/
@nUserNo int,
@nSetMoney bigint,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
SET @nRet = 0
IF EXISTS( SELECT nUserMoney FROM tUserMoney WHERE nUserNo = @nUserNo )
BEGIN
	UPDATE tUserMoney SET nUserMoney = @nSetMoney WHERE nUserNo = @nUserNo
	IF @@ERROR <> 0
		RETURN
END
ELSE
BEGIN
	INSERT INTO tUserMoney VALUES (@nUserNo, @nSetMoney)
	IF @@ERROR <> 0
		RETURN
END
-- DONE
SET @nRet = 1
RETURN


GO
/****** Object:  StoredProcedure [dbo].[p_User_MoneySub]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_User_MoneySub]
/*
Sub user money
2005.5 By CJC
 input:
	see SQL
 output:
	@nRet	1 = OK
	        0 = Error, or Minus value
*/
@nUserNo int,
@nSubMoney bigint,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
IF @nSubMoney < 0
BEGIN
	SET @nRet = 0
	RETURN
END
DECLARE @nUserMoney bigint
EXEC p_User_MoneyGet @nUserNo, @nUserMoney OUTPUT, @nRet OUTPUT
IF @nRet = 0
	RETURN
-- Sub money
SET @nUserMoney = @nUserMoney - @nSubMoney
-- Check minus
IF @nUserMoney < 0
BEGIN
	SET @nRet = 0
	RETURN	
END
EXEC p_User_MoneySet @nUserNo, @nUserMoney, @nRet OUTPUT
-- End


GO
/****** Object:  StoredProcedure [dbo].[p_User_Withdraw]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[p_User_Withdraw]
/*
Set User withdraw money
2006.5 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Miss match UserNo and User's CharNo
	        2 = User Money Sub Failed(Not enough money)
	        3 = Withdraw money faield
	        4 = Get result money faield
*/
@nUserNo int,
@nCharNo int,
@nMoney bigint,
@nResultUserMoney bigint OUTPUT,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
SET @nRet = 0
-- Check UserNo and User's CharNo
DECLARE @nDBUserNo int
SET @nDBUserNo = 0
SELECT @nDBUserNo = nUserNo FROM tCharacter WHERE nCharNo = @nCharNo
IF @nDBUserNo <> @nUserNo
BEGIN
	SET @nRet = 1
	RETURN
END
-- Deposit money
BEGIN TRAN
EXEC p_User_MoneySub @nUserNo, @nMoney, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	SET @nRet = 2
	ROLLBACK TRAN
	RETURN
END
EXEC p_Char_MoneyAdd @nCharNo, @nMoney, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	SET @nRet = 3
	ROLLBACK TRAN
	RETURN
END
EXEC p_User_MoneyGet @nUserNo, @nResultUserMoney OUTPUT, @nRet OUTPUT
IF @nRet <> 1
BEGIN
	SET @nRet = 4
	ROLLBACK TRAN
	RETURN
END
-- Done
COMMIT TRAN
SET @nRet = 0
RETURN


GO
/****** Object:  StoredProcedure [dbo].[p_View_GetData]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
'--------------------------------------------------------------------------------------
' 함수명 : p_View_GetData
' 내  용 : OPTool Char& Item View에서 사용. OPTool에서 입력한 쿼리문에 맞는 데이터 서치.
' 작성자 : 이병기
' 작성일 : 2005년 10월 25일
' 버  젼 : 1.0
' 인  자 :
'			input Parameter
'				@QueryExpr		: OPTool 에서 입력한 쿼리문
'			Output Parameter
'				
'			RETURN_VALUE
'
'--------------------------------------------------------------------------------------
*/
CREATE PROCEDURE [dbo].[p_View_GetData]
	@QueryExpr nvarchar(512)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @SQLCMD nvarchar(512)
	SET @SQLCMD = @QueryExpr
	EXEC sp_executesql @SQLCMD
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Acc_getCharacterList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_Acc_getCharacterList]
AS
BEGIN
	SELECT CONVERT(NVARCHAR(10), GETDATE(), 120) AS dDate, T1.nCharNo, T1.nUserNo, sClassType =
			CASE
				WHEN T2.nClass >= 1 and T2.nClass <= 5 THEN 'Fighter'
				WHEN T2.nClass >= 8 and T2.nClass <= 12 THEN 'Cleric'
				WHEN T2.nClass >= 15 and T2.nClass <= 19 THEN 'Archer'
				WHEN T2.nClass >= 22 and T2.nClass <= 26 THEN 'Mage'
			END,
			T2.nClass, T2.nGender, T1.nLevel, T1.nExp, T1.nPKCount, T1.sID, T3.sName, T4.sID
	  FROM tCharacter T1 
				INNER JOIN tCharacterShape T2 ON T1.nCharNo = T2.nCharNo
				LEFT  JOIN (SELECT GM.nCharNo, G.sName
							  FROM tGuild G, tGuildMember GM
							 WHERE G.nNo = GM.nNo) T3 ON T1.nCharNo = T3.nCharNo
				LEFT  JOIN (SELECT M.nCharNo, M.nPartnerCharNo, C.sID
							  FROM tCharacter C, tMarriage M
							 WHERE C.nCharNo = M.nPartnerCharNo AND C.bDeleted = 0) T4 ON T1.nCharNo = T4.nCharNo
	 WHERE nLevel >= 20 AND nExp > 0 AND bDeleted = 0 AND nAdminLevel = 0
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Attendance_getCallDateList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 捞  抚 : usp_Attendance_getCallDateList
' 累己磊 : Ko Dong Gyun(kodong@gmail.com)
' 累己老 : 2012.2.13
' Description :
'   涝仿等 朝楼荤捞狼 免籍老阑 啊廉咳.
' Parameter :
'	input Parameter
'		@nCharNo       : 某腐磐锅龋
'		@dStartDate    : 矫累老磊
'		@dEndDate      : 辆丰老磊
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'	return Record
'		dAttendanceDate
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Attendance_getCallDateList]
	@nCharNo    int
,	@dStartDate datetime
,	@dEndDate   datetime
,	@nRet       int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	SELECT dAttendanceDate 
	  FROM tAttendance 
	 WHERE nCharNo = @nCharNo
	   AND dAttendanceDate >= @dStartDate 
	   AND dAttendanceDate <= @dEndDate 	
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Attendance_getCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 捞  抚 : usp_Attendance_getCount
' 累己磊 : Ko Dong Gyun(kodong@gmail.com)
' 累己老 : 2012.2.13
' Description :
'   涝仿等 朝楼荤捞狼 免籍 冉荐甫 啊廉咳.
' Parameter :
'	input Parameter
'		@nCharNo       : 某腐磐锅龋
'		@dStartDate    : 矫累老磊
'		@dEndDate      : 辆丰老磊
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'	return Record
'		nAttendanceCount
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Attendance_getCount]
	@nCharNo    int
,	@dStartDate datetime
,	@dEndDate   datetime
,	@nRet       int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	SELECT COUNT(dAttendanceDate) AS nAttendanceCount
	  FROM tAttendance 
	 WHERE nCharNo = @nCharNo
	   AND dAttendanceDate >= @dStartDate 
	   AND dAttendanceDate <= @dEndDate 	
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Attendance_getRewardList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 捞  抚 : usp_Attendance_getRewardList
' 累己磊 : Ko Dong Gyun(kodong@gmail.com)
' 累己老 : 2012.2.13
' Description :
'   涝仿等 朝楼捞饶狼 焊惑 郴开阑 啊廉咳.
' Parameter :
'	input Parameter
'		@nCharNo  : 某腐磐锅龋
'		@dDate    : 老磊
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'	return Record
'		dAttendanceDate
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Attendance_getRewardList]
	@nCharNo    int
,	@dDate      datetime
,	@nRet       int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	SELECT dEventDate, nRewardID  
	  FROM tAttendanceReward  
	 WHERE nCharNo = @nCharNo
	   AND dEventDate > @dDate
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Attendance_setCall]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 捞  抚 : usp_Attendance_setCall
' 累己磊 : Ko Dong Gyun(kodong@gmail.com)
' 累己老 : 2012.2.13
' Description :
'   免籍眉农
' Parameter :
'	input Parameter
'		@nCharNo        : 某腐磐锅龋
'		@dAttendaceDate : 免籍老磊
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-1111 : duplicated call
'				-9999 : db error(insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Attendance_setCall]
	@nCharNo        int
,	@dAttendaceDate datetime
,	@nRet       int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	IF EXISTS(SELECT nCharNo FROM tAttendance WHERE nCharNo = @nCharNo AND dAttendanceDate = @dAttendaceDate) BEGIN
		SET @nRet = -1111
	END
	ELSE BEGIN
		INSERT INTO tAttendance (nCharNo, dAttendanceDate)
		VALUES (@nCharNo, @dAttendaceDate)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -9999
		END
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Attendance_setReward]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 捞  抚 : usp_Attendance_setReward
' 累己磊 : Ko Dong Gyun(kodong@gmail.com)
' 累己老 : 2012.2.13
' Description :
'   焊惑瘤鞭
' Parameter :
'	input Parameter
'		@nCharNo     : 某腐磐锅龋
'		@dRewardDate : 焊惑瘤鞭老磊
'		@nRewardID   : 焊惑酒捞袍ID
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-1111 : duplicated call
'				-9999 : db error(insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Attendance_setReward]
	@nCharNo     int
,	@dEventDate  datetime	
,	@nRewardID   int
,	@nRet        int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	IF EXISTS(SELECT nCharNo FROM tAttendanceReward WHERE nCharNo = @nCharNo AND dEventDate = CAST(@dEventDate as datetime) AND nRewardID = @nRewardID) BEGIN
		SET @nRet = -1111
	END
	ELSE BEGIN
		INSERT INTO tAttendanceReward (nCharNo, dEventDate, dRewardDate, nRewardID)
		VALUES (@nCharNo, @dEventDate, GETDATE(), @nRewardID)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -9999
		END
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_getInventory]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_getInventory
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Parameter :
'	input Parameter
'		@nCharNo    : 캐릭터번호
'		@nAuctionNo : 경매번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3242 : 삭제된 물품은 찾을 수 없습니다.
'	return Record : 경매 보관함(단일레코드)
'		nInventoryType : 보관종류(0:돈/1:구입아이템/2:경매종료아이템/3:경매취소아이템)
'		nItemKey       : 아이템키
'		nItemID        : 아이템식별자
'		dStartDate     : 보관일
'		sSellerID      : 판매자
'		sBidderID      : 구매자
'		nSellPrice     : 판매가격
'		nSellCharge    : 수수료
'		nMoney         : 판매금액(판매가격 - 수수료)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_getInventory]
	@nCharNo    int
,	@nAuctionNo int
,	@nRet       int = 0 output
AS
BEGIN
	SET NOCOUNT ON

	SET @nRet = 0
	
	IF EXISTS(SELECT nCharNo FROM tAuctionInventory WHERE nCharNo = @nCharNo AND nAuctionNo = @nAuctionNo AND bIsDelete = 0) BEGIN	
		SELECT T1.nInventoryType
			 , ISNULL(T1.nItemKey, 0) AS nItemKey
			 , T2.nItemID AS nItemID
			 , T1.dStartDate
			 , (SELECT sID FROM tCharacter WHERE nCharNo = T2.nSellerNo) AS sSellerID
			 , (SELECT sID FROM tCharacter WHERE nCharNo = T2.nBidderNo) AS sBidderID
			 , T2.nSellPrice
			 , ISNULL(T2.nSellCharge, 0) AS nSellCharge
			 , ISNULL(T1.nMoney, 0) AS nMoney
		  FROM tAuctionInventory AS T1 
					INNER JOIN tAuction AS T2 ON T1.nAuctionNo = T2.nAuctionNo 
		 WHERE T1.nCharNo = @nCharNo
		   AND T1.nAuctionNo = @nAuctionNo 
		   AND bIsDelete = 0
	END
	ELSE BEGIN
		SET @nRet = -3242
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_getInventoryList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_getInventoryList
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Parameter :
'	input Parameter
'		@nCharNo : 캐릭터번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'	return Record : 경매 보관함 리스트
'		nAuctionNo     : 경매번호
'		nInventoryType : 보관종류(0:돈/1:구입아이템/2:경매종료아이템/3:경매취소아이템)
'		nTerm          : 보관기간(분)
'		nItemID        : 아이템식별자
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_getInventoryList]
	@nCharNo int
,	@nRet    int = 0 output
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @ret int
	
	SET @nRet = 0
		
	-- 경매장보관함 도착 알림 설정 해제	
	EXEC usp_Character_setAuctionNotice @nCharNo, 0, @ret output
		
	SELECT TOP 200 T1.nAuctionNo
		 , nInventoryType
		 , DATEDIFF(MINUTE, GETDATE(), dEndDate) AS nTerm
		 , ISNULL(T2.nItemID, 65535) AS nItemID
	  FROM tAuctionInventory AS T1, tAuction AS T2
	 WHERE T1.nAuctionNo = T2.nAuctionNo 
	   AND nCharNo = @nCharNo
	   AND dStartDate <= GETDATE()
	   AND dEndDate >= GETDATE()
	   AND bIsDelete = 0
	 ORDER BY dStartDate DESC
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_getItemCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_getItemCount
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Description : 
'	검색 조건에 해당하는 아이템 총 개수를 구함.
' Parameter :
'	input Parameter
'		@nCategoryNo : 카테고리번호
'		@nMinLevel   : 아이템레벨(min)
'		@nMaxLevel   : 아이템레벨(max)
'		@nMinGrade   : 아이템등급(min)
'		@nMaxGrade   : 아이템등급(max)
'		@sItemName   : 검색어(%로 인해 2자리 늘어남)
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_getItemCount]
	@nCategoryNo tinyint = 0
,	@nMinLevel   smallint = 0
,	@nMaxLevel   smallint = 999
,	@nMinGrade   tinyint = 0
,	@nMaxGrade   tinyint = 999
,	@sItemName   nvarchar(64)
,	@nRet        int = 0 output
AS
BEGIN
	SET NOCOUNT ON; 
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
	
	SET @nRet = 0
	
	IF LEN(ISNULL(@sItemName, '')) > 0 BEGIN
		SET @sItemName = '%' + @sItemName + '%'
	END	
	
	SELECT COUNT(T2.nAuctionNo) AS nCnt
	  FROM fn_Auction_getCategory(@nCategoryNo) AS T1
		 , tAuction AS T2
	 WHERE T1.categoryNo = T2.nCategoryNo
	   AND T2.dSellEndDate >= GETDATE()
	   AND T2.nItemLevel >= @nMinLevel
	   AND T2.nItemLevel <= @nMaxLevel 
	   AND T2.nItemGrade >= @nMinGrade 
	   AND T2.nItemGrade <= @nMaxGrade
	   AND (T2.sItemName LIKE @sItemName OR '' = @sItemName)
	   AND T2.nStatus = 0
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_getItemFirstList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_getItemFirstList
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Description : 
'	정렬이 없고 검색어가 없는 1 페이지 리스트
' Parameter :
'	input Parameter
'		@nCategoryNo : 카테고리번호
'		@nMinLevel   : 아이템레벨(min)
'		@nMaxLevel   : 아이템레벨(max)
'		@nMinGrade   : 아이템등급(min)
'		@nMaxGrade   : 아이템등급(max)
'		@nPageNo     : 페이지번호
'		@nPageSize   : 페이지당 표시개수
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_getItemFirstList]
	@nCategoryNo tinyint = 0
,	@nMinLevel   smallint = 0
,	@nMaxLevel   smallint = 999
,	@nMinGrade   tinyint = 0
,	@nMaxGrade   tinyint = 999
,	@nPageNo     int = 1
,	@nPageSize   int = 80
,	@nRet        int = 0 output
AS
BEGIN
	SET NOCOUNT ON; 
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
	
	SET @nRet = 0
	
	SELECT TOP 80 
		   T2.nAuctionNo
		 , DATEDIFF(HOUR, GETDATE(), T2.dSellEndDate) AS nRemainTime
		 , T3.sID
		 , T2.nSellPrice
		 , T2.nItemKey
		 , T2.nItemID
	  FROM fn_Auction_getCategory(@nCategoryNo) AS T1
		 , tAuction AS T2
		 , tCharacter AS T3
	 WHERE T1.categoryNo = T2.nCategoryNo
	   AND T2.nSellerNo = T3.nCharNo 
	   AND T2.dSellEndDate >= GETDATE()
	   AND T2.nItemLevel >= @nMinLevel
	   AND T2.nItemLevel <= @nMaxLevel 
	   AND T2.nItemGrade >= @nMinGrade 
	   AND T2.nItemGrade <= @nMaxGrade
	   AND T2.nStatus = 0
	   AND T3.bDeleted = 0
	 ORDER BY nItemLevel DESC, nItemGrade DESC, nSellPrice DESC, nAuctionNo DESC
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_getItemKeywordList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_getItemKeywordList
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Description : 
'	정렬이 없고 검색어가 있는 1 페이지 리스트
' Parameter :
'	input Parameter
'		@nCategoryNo : 카테고리번호
'		@nMinLevel   : 아이템레벨(min)
'		@nMaxLevel   : 아이템레벨(max)
'		@nMinGrade   : 아이템등급(min)
'		@nMaxGrade   : 아이템등급(max)
'		@sItemName   : 검색어(%로 인해 2자리 늘어남)
'		@nPageNo     : 페이지번호
'		@nPageSize   : 페이지당 표시개수
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_getItemKeywordList]
	@nCategoryNo tinyint = 0
,	@nMinLevel   smallint = 0
,	@nMaxLevel   smallint = 999
,	@nMinGrade   tinyint = 0
,	@nMaxGrade   tinyint = 999
,	@sItemName   nvarchar(64)
,	@nPageNo     int = 1
,	@nPageSize   int = 80
,	@nRet        int = 0 output
AS
BEGIN
	SET NOCOUNT ON; 
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
	
	SET @nRet = 0
	
	SELECT TOP 80 
		   T2.nAuctionNo
		 , DATEDIFF(HOUR, GETDATE(), T2.dSellEndDate) AS nRemainTime
		 , T3.sID
		 , T2.nSellPrice
		 , T2.nItemKey
		 , T2.nItemID
	  FROM fn_Auction_getCategory(@nCategoryNo) AS T1
		 , tAuction AS T2
		 , tCharacter AS T3
	 WHERE T1.categoryNo = T2.nCategoryNo
	   AND T2.nSellerNo = T3.nCharNo 		 
	   AND T2.dSellEndDate >= GETDATE()
	   AND T2.nItemLevel >= @nMinLevel
	   AND T2.nItemLevel <= @nMaxLevel 
	   AND T2.nItemGrade >= @nMinGrade 
	   AND T2.nItemGrade <= @nMaxGrade
	   AND (T2.sItemName LIKE @sItemName OR '' = @sItemName)
	   AND T2.nStatus = 0
	   AND T3.bDeleted = 0
	 ORDER BY nItemLevel DESC, nItemGrade DESC, nSellPrice DESC, nAuctionNo DESC
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_getItemList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_getItemList
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Description : 
'	경매물품 리스트
' Parameter :
'	input Parameter
'		@nCategoryNo : 카테고리번호
'		@nMinLevel   : 아이템레벨(min)
'		@nMaxLevel   : 아이템레벨(max)
'		@nMinGrade   : 아이템등급(min)
'		@nMaxGrade   : 아이템등급(max)
'		@sItemName   : 검색어(%로 인해 2자리 늘어남)
'		@nSortNo     : 정렬조건(0:없음/1:등급/2:레벨/3:기간/4:판매자/5:판매가격)
'		@nSortOption : 정렬방법(0:ASC/1:DESC)
'		@nPageSize   : 페이지당 표시개수
'		@nPageNo     : 페이지번호
'		@nPageSize   : 페이지당 표시개수
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3092 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_getItemList]
	@nCategoryNo tinyint = 0
,	@nMinLevel   smallint = 0
,	@nMaxLevel   smallint = 999
,	@nMinGrade   tinyint = 0
,	@nMaxGrade   tinyint = 100
,	@sItemName   nvarchar(64)
,	@nSortNo     tinyint = 0
,	@bSortOption bit = 0
,	@nPageNo     int = 1
,	@nPageSize   int = 80
,	@nRet        int = 0 output
AS
BEGIN
	SET NOCOUNT ON; 
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

	IF LEN(ISNULL(@sItemName, '')) > 0 BEGIN
		SET @sItemName = '%' + @sItemName + '%'
	END

	IF @nPageNo = 1 AND @nSortNo = 0 BEGIN
		-- 정렬이 없고 페이지가 첫번째인 경우
		IF LEN(ISNULL(@sItemName, '')) = 0 BEGIN
			-- 검색어가 없는 경우
			EXEC usp_Auction_getItemFirstList @nCategoryNo, @nMinLevel, @nMaxLevel, @nMinGrade, @nMaxGrade, @nPageNo, @nPageSize, @nRet output
		END
		ELSE BEGIN
			-- 검색어가 있는경우
			EXEC usp_Auction_getItemKeywordList @nCategoryNo, @nMinLevel, @nMaxLevel, @nMinGrade, @nMaxGrade, @sItemName, @nPageNo, @nPageSize, @nRet output
		END
	END
	ELSE BEGIN
		-- 정렬이 있거나 페이지가 첫번째가 아닌경우
		DECLARE @top int, @order tinyint
		DECLARE @stmt nvarchar(4000), @params nvarchar(500), @sortType nvarchar(200), @reverseType nvarchar(200)

		SET @nRet  = 0
		SET @top   = @nPageNo * @nPageSize

		IF @sItemName IS NULL BEGIN
			SET @sItemName = ''
		END
		/*	2011.01.24 by kodong
			기획팀에서 정렬을 유동적으로 설정할 수 있기를 원하기 때문에 @nSortNo, @nSortOption을
			가공하여 CASE 문에서 유일한 값을 만들어낸다.
			0일때 0, 1 -> 0 으로 만듬
			1일때 0, 1 -> 1, 6 으로 만듬
			2일때 0, 1 -> 2, 7 으로 만듬
			3일때 0, 1 -> 3, 8 으로 만듬
			4일때 0, 1 -> 4, 9 으로 만듬
			5일때 0, 1 -> 5, 10 으로 만듬 */
		IF @nSortNo <> 0 BEGIN
			SET @order = (@nSortNo + (@bSortOption * 5))
		END
		ELSE BEGIN
			SET @order = 0
		END		
		SELECT @sortType = CASE @order
								WHEN  0 THEN 'nItemLevel DESC, nItemGrade DESC, nSellPrice DESC, nAuctionNo DESC '
								WHEN  1 THEN 'sItemName ASC, nItemLevel DESC, nSellPrice DESC, nAuctionNo DESC '
								WHEN  2 THEN 'nItemLevel ASC, nItemGrade DESC, nSellPrice DESC, nAuctionNo DESC '
								WHEN  3 THEN 'nRemainTime ASC, nItemLevel DESC, nItemGrade DESC, nSellPrice DESC, nAuctionNo DESC '
								WHEN  4 THEN 'sID ASC, nItemLevel DESC, nItemGrade DESC, nSellPrice DESC, nAuctionNo DESC '
								WHEN  5 THEN 'nSellPrice ASC, nItemLevel DESC, nItemGrade DESC, nAuctionNo DESC '
								WHEN  6 THEN 'sItemName DESC, nItemLevel DESC, nSellPrice DESC, nAuctionNo DESC '
								WHEN  7 THEN 'nItemLevel DESC, nItemGrade DESC, nSellPrice DESC, nAuctionNo DESC '
								WHEN  8 THEN 'nRemainTime DESC, nItemLevel DESC, nItemGrade DESC, nSellPrice DESC, nAuctionNo DESC '
								WHEN  9 THEN 'sID DESC, nItemLevel DESC, nItemGrade DESC, nSellPrice DESC, nAuctionNo DESC '
								WHEN 10 THEN 'nSellPrice DESC, nItemLevel DESC, nItemGrade DESC, nAuctionNo DESC '								
							END,
			   @reverseType = CASE @order
								WHEN  0 THEN 'nItemLevel ASC, nItemGrade ASC, nSellPrice ASC, nAuctionNo ASC '
								WHEN  1 THEN 'sItemName DESC, nItemLevel ASC, nSellPrice ASC, nAuctionNo ASC '
								WHEN  2 THEN 'nItemLevel DESC, nItemGrade ASC, nSellPrice ASC, nAuctionNo ASC '
								WHEN  3 THEN 'nRemainTime DESC, nItemLevel ASC, nItemGrade ASC, nSellPrice ASC, nAuctionNo ASC '
								WHEN  4 THEN 'sID DESC, nItemLevel ASC, nItemGrade ASC, nSellPrice ASC, nAuctionNo ASC '
								WHEN  5 THEN 'nSellPrice DESC, nItemLevel ASC, nItemGrade ASC, nAuctionNo ASC '
								WHEN  6 THEN 'sItemName ASC, nItemLevel ASC, nSellPrice ASC, nAuctionNo ASC '
								WHEN  7 THEN 'nItemLevel ASC, nItemGrade ASC, nSellPrice ASC, nAuctionNo ASC '
								WHEN  8 THEN 'nRemainTime ASC, nItemLevel ASC, nItemGrade ASC, nSellPrice ASC, nAuctionNo ASC '
								WHEN  9 THEN 'sID ASC, nItemLevel ASC, nItemGrade ASC, nSellPrice ASC, nAuctionNo ASC '
								WHEN 10 THEN 'nSellPrice ASC, nItemLevel ASC, nItemGrade ASC, nAuctionNo ASC '								
							END 

		SET @stmt = N''
		SET @stmt = @stmt + 'SELECT nAuctionNo, nRemainTime, sID, nSellPrice, nItemKey, nItemID '
		SET @stmt = @stmt + '  FROM ( '
		SET @stmt = @stmt + '		SELECT TOP ' + CAST(@nPageSize AS NVARCHAR)+ ' T3.* '
		SET @stmt = @stmt + '		  FROM ( '
		SET @stmt = @stmt + '				SELECT TOP ' + CAST(@top AS NVARCHAR)
		SET @stmt = @stmt + '					   T2.nAuctionNo '
		SET @stmt = @stmt + '					 , DATEDIFF(HOUR, GETDATE(), T2.dSellEndDate) AS nRemainTime '
		SET @stmt = @stmt + '					 , T3.sID '
		SET @stmt = @stmt + '					 , T2.nSellPrice '
		SET @stmt = @stmt + '					 , T2.nItemKey '
		SET @stmt = @stmt + '					 , T2.nItemID '
		SET @stmt = @stmt + '					 , T2.nItemLevel '
		SET @stmt = @stmt + '					 , T2.nItemGrade '
		SET @stmt = @stmt + '					 , T2.sItemName '
		SET @stmt = @stmt + '				  FROM fn_Auction_getCategory(@nCategoryNo) AS T1 '
		SET @stmt = @stmt + '					 , tAuction AS T2 '
		SET @stmt = @stmt + '					 , tCharacter AS T3 '		
		SET @stmt = @stmt + '				 WHERE T1.categoryNo   =  T2.nCategoryNo '
		SET @stmt = @stmt + '				   AND T2.nSellerNo    =  T3.nCharNo '		
		SET @stmt = @stmt + '				   AND T2.dSellEndDate >= GETDATE() '
		SET @stmt = @stmt + '				   AND T2.nItemLevel   >= @nMinLevel '
		SET @stmt = @stmt + '				   AND T2.nItemLevel   <= @nMaxLevel '
		SET @stmt = @stmt + '				   AND T2.nItemGrade   >= @nMinGrade '
		SET @stmt = @stmt + '				   AND T2.nItemGrade   <= @nMaxGrade '
		SET @stmt = @stmt + '				   AND (T2.sItemName LIKE @sItemName OR ''' + ''' = @sItemName) '
		SET @stmt = @stmt + '				   AND T2.nStatus      =  0 '
		SET @stmt = @stmt + '				   AND T3.bDeleted     =  0 '		
		SET @stmt = @stmt + '				 ORDER BY ' + @sortType 
		SET @stmt = @stmt + '				) AS T3 '
		SET @stmt = @stmt + '		 ORDER BY ' + @reverseType 
		SET @stmt = @stmt + '		) AS T4 '
		SET @stmt = @stmt + ' ORDER BY ' + @sortType 
		SET @params = N'@top int, @nPageSize int, @nCategoryNo tinyint, @nMinLevel smallint, @nMaxLevel smallint, @nMinGrade tinyint, @nMaxGrade tinyint, @sItemName nvarchar(66)'
		EXEC sp_executesql @stmt, @params, @top, @nPageSize, @nCategoryNo, @nMinLevel, @nMaxLevel, @nMinGrade, @nMaxGrade, @sItemName
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_getSellerItemList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_getSellerItemList
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Parameter :
'	input Parameter
'		@nSellerNo : 판매자
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'	return Record : 판매자의 판매아이템 리스트
'		nAuctionNo : 경매번호
'		nTerm      : 판매기간
'		nSellPrice : 판매가격
'		nItemKey   : 아이템키
'		nItemID    : 아이템식별자
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_getSellerItemList]
	@nSellerNo int
,	@nRet      int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0

	SELECT nAuctionNo
		 , DATEDIFF(MINUTE, GETDATE(), dSellEndDate) AS nTerm
		 , nSellPrice
		 , nItemKey
		 , nItemID
	  FROM tAuction
	 WHERE nSellerNo = @nSellerNo
	   AND dSellStartDate <= GETDATE()
	   AND dSellEndDate >= GETDATE()
	   AND nStatus = 0
	 ORDER BY nTerm
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_setBidding]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_setBidding
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Parameter :
'	input Parameter
'		@nAuctionNo     : 경매번호
'		@nBidderNo      : 구매자
'		@nSellPriceRate : 판매수수료(1/1000)
'		@nInventoryTerm : 경매보관함 보관일(hour)
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3231 : 자신의 물건을 구매할 수 없습니다.
'				-3232 : 구매자의 게임머니가 부족합니다.
'				-3233 : db error (update) 경매물품 낙찰기록에 실패하였습니다.
'				-3234 : db error (update) 구매자의 게임머니 차감에 실패하였습니다.
'				-3235 : db error (update) 아이템 상태변경에 실패하였습니다.(판매자 -> 구매자)
'				-3236 : db error (insert) 구매자에게 아이템 지급에 실패하였습니다.
'				-3237 : db error (insert) 판매자에게 게임머니 지급에 실패하였습니다.
'				-3238 : 진행중인 경매물품이 아닌경우 구매할 수 없습니다.
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_setBidding]
	@nAuctionNo     int
,	@nBidderNo      int
,	@nSellPriceRate int
,	@nInventoryTerm int
,	@nRet           int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000
	
	DECLARE @sellerNo int, @sellPrice bigint, @itemKey bigint, @itemID int, @isDelete tinyint
	DECLARE @bidderMoney bigint
	DECLARE @sellCharge bigint
	DECLARE @storageType tinyint, @inventoryType tinyint
	DECLARE @ret int
	
	SET @storageType = 101 -- 경매 보관함
	SET @nRet = 0
	
	IF EXISTS(SELECT nAuctionNo 
				FROM tAuction 
			   WHERE nAuctionNo = @nAuctionNo 
				 AND dSellStartDate <= GETDATE()
				 AND dSellEndDate >= GETDATE()
				 AND nStatus = 0) BEGIN
		-- 경매정보를 가져옴
		SELECT @sellerNo = T1.nSellerNo, @sellPrice = T1.nSellPrice, @itemKey = T1.nItemKey , @itemID = T1.nItemID, @isDelete = T2.bDeleted
		  FROM tAuction AS T1 INNER JOIN tCharacter AS T2 ON T1.nSellerNo = T2.nCharNo 
		 WHERE nAuctionNo = @nAuctionNo 
		IF @sellerNo = @nBidderNo BEGIN
			SET @nRet = -3231
			RETURN
		END

		IF @isDelete = 0 BEGIN
			BEGIN TRAN
					 
			-- 구매자 게임머니 확인
			SELECT @bidderMoney = ISNULL(nMoney, 0) FROM tCharacter WHERE nCharNo = @nBidderNo AND bDeleted = 0
			IF @sellPrice > @bidderMoney BEGIN
				ROLLBACK TRAN
				SET @nRet = -3232
				RETURN
			END

			-- 경매 아이템 낙찰기록
			SET @sellCharge = ROUND(((@sellPrice * @nSellPriceRate) / 1000), 1)
			IF @sellCharge < 1 BEGIN
				SET @sellCharge = 1
			END
			
			-- 낙찰여부 기록
			UPDATE tAuction 
			   SET sys_update_date = GETDATE()
				 , nBidderNo = @nBidderNo
				 , dBidDate = GETDATE()
				 , nSellCharge = @sellCharge 
				 , nStatus  = 1
			 WHERE nAuctionNo = @nAuctionNo 
			   AND nStatus = 0
			IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
				ROLLBACK TRAN
				SET @nRet = -3233
				RETURN			
			END

			-- 구매자 게임머니 차감
			UPDATE tCharacter
			   SET nMoney = nMoney - @sellPrice
			 WHERE nCharNo = @nBidderNo 
			IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
				ROLLBACK TRAN
				SET @nRet = -3234
				RETURN			
			END
			
			-- 경매 아이템 소유권이전 및 보관함으로 이동
			UPDATE tItem
			   SET nOwner = @nBidderNo 
				 , nStorageType = @storageType 
			 WHERE nItemKey = @itemKey
			   AND nStorageType = 100 
			IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
				ROLLBACK TRAN
				SET @nRet = -3235
				RETURN			
			END
			
			-- 구매자 아이템 지급(경매보관함)
			SET @inventoryType = 1
			INSERT INTO tAuctionInventory (nCharNo, nAuctionNo, nInventoryType, dEndDate, nItemKey)
			VALUES (@nBidderNo, @nAuctionNo, @inventoryType, DATEADD(HOUR, @nInventoryTerm, GETDATE()), @itemKey)
			IF @@ERROR <> 0 BEGIN
				ROLLBACK TRAN
				SET @nRet = -3236
				RETURN	
			END
			EXEC usp_Character_setAuctionNotice @nBidderNo, 1, @ret output	 		 

			-- 판매자 게임머니 지급(경매보관함)
			SET @inventoryType = 0
			INSERT INTO tAuctionInventory (nCharNo, nAuctionNo, nInventoryType, dEndDate, nMoney)
			VALUES (@sellerNo, @nAuctionNo, @inventoryType, DATEADD(HOUR, @nInventoryTerm, GETDATE()), @sellPrice - @sellCharge)
			IF @@ERROR <> 0 BEGIN
				ROLLBACK TRAN
				SET @nRet = -3237
				RETURN	
			END
			EXEC usp_Character_setAuctionNotice @sellerNo, 1, @ret output
			
			SELECT @sellerNo AS nSellerNo, @itemID AS nItemID, @sellPrice AS nSellPrice
			
			COMMIT TRAN
		END
		ELSE BEGIN
			SET @nRet = -3247
			RETURN
		END
	END
	ELSE BEGIN
		-- 이미 판매된 아이템
		SET @nRet = -3238
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_setCancel]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_setCancel
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Parameter :
'	input Parameter
'		@nAuctionNo     : 경매번호
'		@nSellerNo      : 판매자
'		@nInventoryTerm : 경매보관함 보관일(hour)
'		@nCancelType    : 취소사유
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3226 : 진행중인 경매물품이 아닌경우 취소할 수 없습니다.
'				-3227 : 자신의 물건이 아닌경우 취소할 수 없습니다.
'				-3228 : db error (update) 경매물품 취소에 실패하였습니다.
'				-3229 : db error (update) 아이템 상태변경에 실패하였습니다.(경매장 -> 보관소)
'				-3230 : db error (insert) 취소된 아이템을 보관소에 지급하는데 실패하였습니다.
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_setCancel]
	@nAuctionNo     int
,	@nSellerNo      int
,	@nInventoryTerm int
,	@nCancelType    tinyint
,	@nRet           int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @sellerNo int, @itemKey bigint, @itemID int
	DECLARE @storageType tinyint
	DECLARE @ret int
	
	SET @storageType = 101 -- 경매보관함
	SET @nRet = 0

	SELECT @sellerNo = nSellerNo, @itemKey = nItemKey, @itemID = nItemID
	  FROM tAuction 
     WHERE nAuctionNo = @nAuctionNo 
	   AND nStatus = 0
	IF @sellerNo IS NOT NULL BEGIN
		IF @sellerNo <> @nSellerNo BEGIN
			SET @nRet = -3227
			RETURN
		END
		
		BEGIN TRAN
		
		-- 경매장 판매취소 기록
		UPDATE tAuction SET sys_update_date = GETDATE(), nStatus = @nCancelType WHERE nAuctionNo = @nAuctionNo AND nStatus = 0
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			ROLLBACK TRAN
			SET @nRet = -3228
			RETURN
		END
		
		-- 경매보관소로 아이템 이동
		UPDATE tItem SET nStorageType = @storageType WHERE nItemKey = @itemKey AND nStorageType = 100
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			ROLLBACK TRAN
			SET @nRet = -3229
			RETURN
		END
		
		-- 판매자 아이템 지급(경매보관함)
		INSERT INTO tAuctionInventory (nCharNo, nAuctionNo, nInventoryType, dEndDate, nItemKey)
		VALUES (@sellerNo, @nAuctionNo, @nCancelType, DATEADD(HOUR, @nInventoryTerm, GETDATE()), @itemKey)
		IF @@ERROR <> 0 BEGIN
			ROLLBACK TRAN
			SET @nRet = -3230
			RETURN	
		END
		EXEC usp_Character_setAuctionNotice @sellerNo, 1, @ret output				
		
		COMMIT TRAN		
	END
	ELSE BEGIN
		SET @nRet = -3226
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_setEnd]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_setEnd
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Parameter :
'	input Parameter
'		@nInventoryTerm : 경매보관함 보관일(hour)
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'	return Record : 판매종료 된 경매리스트
'		charNo    : 캐릭터번호
'		auctionNo : 경매번호
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_setEnd]
	@nInventoryTerm int
,	@nRet           int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @auctionNo int, @sellerNo int, @itemID int
	DECLARE @cancelType tinyint
	DECLARE @ret int
	DECLARE @endList TABLE (
		charNo    int
	,	auctionNo int
	,	itemID    int
	)

	SET @nRet = 0
	SET @cancelType = 2 -- 경매종료(시간만료)
	
	DECLARE CUR_AUCTION CURSOR FORWARD_ONLY
	FOR
		SELECT nAuctionNo, nSellerNo, nItemID
		  FROM tAuction
		 WHERE dSellEndDate < GETDATE()
		   AND nStatus = 0

	OPEN CUR_AUCTION
	
	FETCH FROM CUR_AUCTION INTO @auctionNo, @sellerNo, @itemID
	WHILE @@FETCH_STATUS = 0 BEGIN
		SET @ret = 0
		EXEC usp_Auction_setCancel @auctionNo, @sellerNo, @nInventoryTerm, @cancelType, @ret output
		IF @ret = 0 BEGIN
			INSERT INTO @endList VALUES (@sellerNo, @auctionNo, @itemID)
		END
		
		FETCH FROM CUR_AUCTION INTO @auctionNo, @sellerNo, @itemID
	END

	CLOSE CUR_AUCTION
	DEALLOCATE CUR_AUCTION
	
	SELECT charNo, auctionNo, itemID FROM @endList ORDER BY charNo ASC
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_setRegist]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_setRegist
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Parameter :
'	input Parameter
'		@nSellerNo     : 판매자
'		@nItemID       : 아이템식별자
'		@sItemName     : 아이템명
'		@nItemLevel    : 아이템레벨
'		@nItemGrade    : 아이템등급
'		@nCategoryNo   : 카테고리번호
'		@nRegistration : 등록비
'		@nTerm         : 판매기간(분)
'		@nSellPrice    : 판매가격
'		@nItemKey      : 아이템키
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3211 : 판매자가 삭제되었거나 존재하지 않습니다.
'				-3212 : 존재하지 않는 아이템입니다.
'				-3213 : 판매금액이 최소단위보다 작습니다.
'				-3221 : db error (insert) 검색테이블 등록에 실패하였습니다.
'				-3224 : db error (insert) 경매물품 등록에 실패하였습니다.
'				-3225 : db error (insert) 아이템 상태변경에 실패하였습니다.(인벤토리 -> 경매장)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_setRegist]
	@nSellerNo     int
,	@nItemID       int
,	@sItemName     nvarchar(64)
,	@nItemLevel    smallint
,	@nItemGrade    tinyint
,	@nCategoryNo   tinyint
,	@nRegistration bigint
,	@nTerm         int
,	@nSellPrice    bigint
,	@nItemKey      bigint
,	@nLimitCount   int
,	@nRet          int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	DECLARE @charNo int, @auctionNo int, @chkCount int, @ret int
	DECLARE @money bigint
	DECLARE @storageType tinyint
	
	SET @storageType = 100 -- 경매장 StorageType	
	SET @nRet = 0
	SET @ret  = 0
	
	SELECT @charNo = nCharNo, @money = nMoney FROM tCharacter WHERE nCharNo = @nSellerNo AND bDeleted = 0
	IF @charNo IS NULL BEGIN
		SET @nRet = -3211
		RETURN
	END
	IF NOT EXISTS(SELECT nItemKey FROM tItem WITH(NOLOCK) WHERE nItemKey = @nItemKey AND nFlags = 0) BEGIN
		SET @nRet = -3212
		RETURN
	END	
	IF @nSellPrice < 1 BEGIN
		SET @nRet = -3213
		RETURN
	END
	IF @money < @nRegistration BEGIN
		SET @nRet = -3244
		RETURN
	END
	SELECT @chkCount = COUNT(nAuctionNo) FROM tAuction WHERE dSellEndDate >= GETDATE() AND nStatus = 0 AND nSellerNo = @nSellerNo
	IF @chkCount >= @nLimitCount BEGIN
		SET @nRet = -3246
		RETURN	
	END	

	-- 경매 등록
	BEGIN TRAN
	
	-- 경매물 등록
	INSERT INTO tAuction (nCategoryNo, nSellerNo, nRegistration, dSellEndDate, nSellPrice, nItemKey, nItemID, nItemLevel, nItemGrade, sItemName)
	VALUES (@nCategoryNo, @nSellerNo, @nRegistration, DATEADD(MINUTE , @nTerm, GETDATE()), @nSellPrice, @nItemKey, @nItemID, @nItemLevel, @nItemGrade, @sItemName)
	IF @@ERROR <> 0 OR SCOPE_IDENTITY() <= 0 BEGIN
		ROLLBACK TRAN
		SET @nRet = -3224
		RETURN
	END	
	ELSE BEGIN
		SET @auctionNo = SCOPE_IDENTITY()
		
		UPDATE tCharacter
		   SET nMoney = nMoney - @nRegistration 
		 WHERE nCharNo = @nSellerNo
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			ROLLBACK TRAN
			SET @nRet = -3245
			RETURN
		END
		
		UPDATE tItem
		   SET nStorageType = @storageType 
		     , nFlags = @auctionNo 
		 WHERE nItemKey = @nItemKey
		   AND nFlags = 0
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			ROLLBACK TRAN
			SET @nRet = -3225
			RETURN
		END

		COMMIT TRAN
		SELECT @auctionNo AS nAuctionNo
	END 
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_withdrawInventoryItem]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_withdrawInventoryItem
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Parameter :
'	input Parameter
'		@nCharNo      : 구매자
'		@nAuctionNo   : 경매번호
'		@nStorageType : 인벤토리종류
'		@nStorage     : 인벤토리번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3239 : 보관일이 지난 물품은 찾을 수 없습니다.
'				-3241 : db error (update) 보관함 인출 기록에 실패하였습니다.
'				-3242 : 삭제된 물품은 찾을 수 없습니다.
'				-3240 : db error (update) 보관함에서 아이템 지급에 실패하였습니다.
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_withdrawInventoryItem]
	@nCharNo      int
,	@nAuctionNo   int
,	@nStorageType tinyint
,	@nStorage     smallint
,	@nRet         int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @itemKey bigint
	DECLARE @endDate datetime
	
	SET @nRet = 0
	
	SELECT @itemKey = nItemKey, @endDate = dEndDate 
	  FROM tAuctionInventory 
	 WHERE nCharNo = @nCharNo 
	   AND nAuctionNo = @nAuctionNo 
	   AND bIsDelete = 0
	IF @itemKey IS NOT NULL BEGIN
		-- 보관일 체크
		IF @endDate < GETDATE() BEGIN
			SET @nRet = -3239
			RETURN
		END
		
		-- 아이템 지급
		IF EXISTS(SELECT nItemKey 
					FROM tItem 
				   WHERE nOwner = @nCharNo 
					 AND nStorageType = @nStorageType 
					 AND nStorage = @nStorage
					 AND nFlags = 0) BEGIN
			SET @nRet = -2521
			RETURN
		END	
		ELSE BEGIN	
			BEGIN TRAN
				
			UPDATE tItem
			   SET nStorageType = @nStorageType
				 , nStorage = @nStorage
				 , nFlags = 0 
			 WHERE nItemKey = @itemKey
			   AND nStorageType = 101
			   AND nFlags <> 0
			IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
				ROLLBACK TRAN
				SET @nRet = -3243
				RETURN
			END
			
			-- 보관함 인출 기록
			UPDATE tAuctionInventory 
			   SET sys_update_date = GETDATE()
				 , bIsDelete = 1
				 , dDeleteDate = GETDATE()
			 WHERE nCharNo = @nCharNo 
			   AND nAuctionNo = @nAuctionNo 
			   AND bIsDelete = 0
			IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
				ROLLBACK TRAN
				SET @nRet = -3241
				RETURN
			END
			
			COMMIT TRAN
		END
				   
		SELECT nItemKey, nItemID FROM tItem WHERE nItemKey = @itemKey
	END
	ELSE BEGIN
		SET @nRet = -3242
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Auction_withdrawInventoryMoney]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Auction_withdrawInventoryMoney
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.21.
' Parameter :
'	input Parameter
'		@nCharNo    : 캐릭터번호
'		@nAuctionNo : 경매번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3239 : 보관일이 지난 물품은 찾을 수 없습니다.
'				-3240 : db error (update) 보관함에서 게임머니 지급에 실패하였습니다.
'				-3241 : db error (update) 보관함 인출 기록에 실패하였습니다.
'				-3242 : 삭제된 물품은 찾을 수 없습니다.
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Auction_withdrawInventoryMoney]
	@nCharNo     int
,	@nAuctionNo  int
,	@nRet        int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @money bigint
	DECLARE @endDate datetime
	
	SET @nRet = 0
	
	SELECT @money = nMoney, @endDate = dEndDate 
	  FROM tAuctionInventory 
	 WHERE nCharNo = @nCharNo 
	   AND nAuctionNo = @nAuctionNo 
	   AND bIsDelete = 0
	IF @money IS NOT NULL BEGIN
		-- 보관일 체크
		IF @endDate < GETDATE() BEGIN
			SET @nRet = -3239
			RETURN
		END
		
		BEGIN TRAN
		
		-- 게임머니 지급
		UPDATE tCharacter
		   SET nMoney = nMoney + @money
		 WHERE nCharNo = @nCharNo
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			ROLLBACK TRAN
			SET @nRet = -3240
			RETURN
		END
		
		-- 보관함 인출 기록
		UPDATE tAuctionInventory 
		   SET sys_update_date = GETDATE()
			 , bIsDelete = 1
		     , dDeleteDate = GETDATE()
		 WHERE nCharNo = @nCharNo 
		   AND nAuctionNo = @nAuctionNo 
		   AND bIsDelete = 0
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			ROLLBACK TRAN
			SET @nRet = -3241
			RETURN
		END
				   
		COMMIT TRAN
		
		SELECT @money AS nMoney
	END
	ELSE BEGIN
		SET @nRet = -3242
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Char_chkCharNo]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Char_chkCharNo
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2008.8.27
' Description :
'   미국, 독일에서 문제된 캐릭터 정보가 서로 일치하지 않는 문제를 해결하기 위함
'	
'	월드매니저 서버에서 존 서버로 연결이 넘어갈 때 넘어온 정보가 캐릭터 데이터베이스
'	정보와 일치하는지를 체크하기 위함.
'	기타 여러가지 정보를 추가 체크할 수 있으나 nCharNo 와 sID 체크만으로 가능한 것으로
'	판단됨.
' Parameter :
'	input Parameter
'		@nCharNo : 캐릭터번호
'		@sID     : 캐릭터명
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'-------------------------------------------------------------------------------------*/
CREATE  PROCEDURE [dbo].[usp_Char_chkCharNo]
	@nCharNo int
,	@sID     nvarchar(40)
,	@nRet    int = 0 output
AS
BEGIN
	SET NOCOUNT ON

	IF EXISTS(SELECT nCharNo FROM tCharacter WHERE nCharNo = @nCharNo AND sID = @sID)
		SET @nRet = 0
	ELSE
		SET @nRet = -1


	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Char_GetDisposition]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Created by khris <khris@khrislog.net>
-- Last modified: 2009 10 20

CREATE PROCEDURE [dbo].[usp_Char_GetDisposition]
	@nCharNo INT
AS

BEGIN
	SET NOCOUNT ON

	-- 성향이 변경되는 일을 하지 않았을 경우 기록이 없을수도 있다
	IF EXISTS(SELECT * FROM tCharacterDisposition WHERE nCharNo=@nCharNo)
	BEGIN
		-- 자신의 성향 기록이 존재 한다면
		SELECT nDisposition, nKillCount, nKillPoint, nChaosPoint, nNeutralTime FROM tCharacterDisposition WHERE nCharNo=@nCharNo;
	END
	ELSE
	BEGIN
		-- 존재하지 않는다면 성향은 D_LAWFUL(1), `킬 카운트 & 킬 포인트 & 카오스 포인트`는 0으로 돌려준다
		SELECT 1, 0, 0, 0, 0;
	END

	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Char_SetDisposition]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Created by khris <khris@khrislog.net>
-- Last modified: 2009 10 20

CREATE PROCEDURE [dbo].[usp_Char_SetDisposition]
	@nCharNo INT,
	@nDisposition TINYINT,
	@nKillCount INT,
	@nKillPoint INT,
	@nChaosPoint INT,
	@nNeutralTime INT
AS

BEGIN
	SET NOCOUNT ON

	-- 성향이 변경되는 일을 하지 않았을 경우 기록이 없을수도 있다
	IF EXISTS(SELECT * FROM tCharacterDisposition WHERE nCharNo=@nCharNo)
	BEGIN
		-- 자신의 성향 기록이 존재 한다면
		UPDATE tCharacterDisposition SET nDisposition=@nDisposition, nKillCount=@nKillCount, nKillPoint=@nKillPoint, nChaosPoint=@nChaosPoint, nNeutralTime=@nNeutralTime WHERE nCharNo=@nCharNo;
	END
	ELSE
	BEGIN
		-- 존재하지 않는다면 삽입
		INSERT INTO tCharacterDisposition VALUES (@nCharNo,	@nDisposition, @nKillCount, @nKillPoint, 	@nChaosPoint, @nNeutralTime);
	END

	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_chkKeyMap]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_chkKeyMap
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.09.13
' Description :
'   캐릭터의 단축키를 저장한다.
'	클라이언트에서 변경된 단축키만 보내오기로 함.
'	데이터베이스에서는 변경된 값을 체크하지 않음(성능상 이슈는 없음)
' Parameter :
'	input Parameter
'		@nCharNo      : 캐릭터번호
'		@nFunctionNo  : 기능번호
'		@nExtendedKey : 확장키(Ctrl, Alt, Shift)
'		@nASCIICode   : 실제키
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3092 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_chkKeyMap]
	@nCharNo      int
,	@nRet         int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	SET @nRet = 0

	IF EXISTS(SELECT nCharNo FROM tCharacterKeyMap WHERE nCharNo = @nCharNo) BEGIN
		SELECT 1
	END
	ELSE BEGIN
		SELECT 0
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_getChangeIDList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_getChangeIDList
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.7.28.
' Description :
'   서버메모리에 미반영된 캐릭터정보를 가져옴
' Parameter :
'	input Parameter
'		@nUserNo : 유저번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_getChangeIDList]
	@nUserNo int
,	@nRet    int = 0 output
AS
BEGIN
	SET NOCOUNT ON

	SET @nRet = 0
	
	SELECT nRowNo, nUserNo, nCharNo, bInit
	  FROM tCharacterChangeID
	 WHERE nUserNo = @nUserNo AND bFlag = 0
	   
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_getGameOption]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_getGameOption
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2011.6.29.
' Description :
'   게임옵션을 가져옴.
'	유저의 선택에 따라 변경된 내용이 있을때는 초기값 테이블과 조인하여 가져오고
'	아무 변경 사항이 없을경우 초기 테이블 값을 그대로 가져옴.
' Parameter :
'	input Parameter
'		@nCharNo      : 캐릭터번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_getGameOption]
	@nCharNo int
,	@nRet    int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	IF EXISTS(SELECT nCharNo FROM tCharacterGameOption WHERE nCharNo = @nCharNo) BEGIN
		SELECT T1.nOptionNo, ISNULL(T2.nValue, T1.nDefaultValue) AS nValue
		  FROM tGameOptionInit AS T1 LEFT OUTER JOIN (
				SELECT * FROM tCharacterGameOption WHERE nCharNo = @nCharNo) AS T2
					ON T1.nOptionNo = T2.nOptionNo
		 WHERE T1.bIsActive = 1
	END
	ELSE BEGIN
		SELECT nOptionNo, nDefaultValue AS nValue
		  FROM tGameOptionInit 
		 WHERE bIsActive = 1
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_getIDGroupCountList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 檜  葷 : usp_Character_getIDGroupCountList
' 濛撩濠 : Ko Dong Gyun(kodong@gmail.com)
' 濛撩橾 : 2010.11.9
'   檣蝶欐蝶湍瞪 斜瑜滌 霤陛 熱 
' Parameter :
'	input Parameter
'		@nCharNo      : 議葛攪廓
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3191 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_getIDGroupCountList]
	@nCharNo      int
,	@nRet         int = 0 output
AS
BEGIN
	SET NOCOUNT ON

	SET @nRet = 0
	
	SELECT sIDGroup, nCount 
	  FROM tInstanceDungeonCount 
	 WHERE nCharNo = @nCharNo
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_getItemActionCoolTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_getItemActionCoolTime
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.08.26.
' Description :
'	존링크 또는 로그아웃시 저장된 재사용 대기시간을 가져온다.
'	단, 이미 재사용 대기시간이 초기화된 경우 이를 데이터베이스에서 삭제 후 가져온다.
' Parameter :
'	input Parameter
'		@nCharNo      : 캐릭터번호
'		@nActionGroup : 아이템 액션 그룹
'		@dEndTime     : 종료시간
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3039 : db error (delete)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_getItemActionCoolTime]
	@nCharNo      int
,	@nRet         int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	IF EXISTS(SELECT nCharNo FROM tItemActionCoolTime WHERE nCharNo = @nCharNo AND dEndTime < GETDATE()) BEGIN
		BEGIN TRAN
		
		DELETE FROM tItemActionCoolTime WHERE nCharNo = @nCharNo AND dEndTime < GETDATE()
		IF @@ERROR <> 0 OR @@ROWCOUNT = 0 BEGIN
			SET @nRet = -3294
			ROLLBACK TRAN
			RETURN
		END	
		
		SELECT nCharNo, nActionGroup, dEndTime FROM tItemActionCoolTime WHERE nCharNo = @nCharNo
		
		COMMIT TRAN
	END
	ELSE BEGIN
		SELECT nCharNo, nActionGroup, dEndTime FROM tItemActionCoolTime WHERE nCharNo = @nCharNo 
	END
	
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_getKeyMap]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_getKeyMap
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.09.13
' Description :
'   캐릭터의 단축키를 저장한다.
'	클라이언트에서 변경된 단축키만 보내오기로 함.
'	데이터베이스에서는 변경된 값을 체크하지 않음(성능상 이슈는 없음)
' Parameter :
'	input Parameter
'		@nCharNo      : 캐릭터번호
'		@nFunctionNo  : 기능번호
'		@nExtendedKey : 확장키(Ctrl, Alt, Shift)
'		@nASCIICode   : 실제키
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3092 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_getKeyMap]
	@nCharNo      int
,	@nRet         int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	SET @nRet = 0

	IF EXISTS(SELECT nCharNo FROM tCharacterKeyMap WHERE nCharNo = @nCharNo) BEGIN
		SELECT nFunctionNo, nExtendedKey, nASCIICode
		  FROM tCharacterKeyMap 
		 WHERE nCharNo = @nCharNo 
	END
	ELSE BEGIN
		SET @nRet = -2725
		RETURN
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_getShortCutList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_getShortCutList
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.09.13
' Description :
'   캐릭터의 숏컷데이터를 가져옴
' Parameter :
'	input Parameter
'		@nCharNo      : 캐릭터번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-2721 : not found nCharNo
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_getShortCutList]
	@nCharNo int,
	@nRet    int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	IF EXISTS(SELECT nCharNo FROM tCharacter WHERE nCharNo = @nCharNo AND bDeleted = 0) BEGIN
		SELECT nSlotNo, nCodeNo, nValue
		  FROM tCharacterShortCut
		 WHERE nCharNo = @nCharNo AND nCodeNo > 0
	END
	ELSE BEGIN
		SET @nRet = -2721
	END
	
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_getSingleOption]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 檜  葷 : usp_Character_getSingleOption
' 濛撩濠 : Ko Dong Gyun(kodong@gmail.com)
' 濛撩橾 : 2010.10.18.
'   議葛攪曖 欽橾鏽歲 褫暮高菟擊 陛螳褥
'	億煎遴 鐘筆隴 蹺陛衛 欽橾鏽歲戲煎 脹 褫暮高擊 陛韓 唳辦 tCharacterSingleOption
'	纔檜綰縑 蹺陛 高擊 陛螳螃朝 煎衛盪朝 檜 煎衛盪煎 鱔橾.
' 熱薑橾 : 2011.01.17
'	唳衙濰 蹺陛煎 檣 SELECT 瞰縑 bAuction 鏽歲 蹺陛
' 熱薑橾 : 2011.11.9
'	韁渾蠡蝶 偃摹寰(衙蘆)縑 評艇 綠衙傘 嶸盪 謙猿衛除 dNoMannerEndDate 鏽歲 蹺陛
' Parameter :
'	input Parameter
'		@nCharNo      : 議葛攪廓
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3191 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_getSingleOption]
	@nCharNo      int
,	@nRet         int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	SET @nRet = 0

	IF NOT EXISTS(SELECT nCharNo FROM tCharacterSingleOption WHERE nCharNo = @nCharNo) BEGIN
		INSERT INTO tCharacterSingleOption (nCharNo)
		VALUES (@nCharNo)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3192
			RETURN
		END
	END

	SELECT bMysteryBolt
		,  bAutoPick 
		,  dRestExpLastExecuteTime
		,  nChatBan
		,  bAuction
		,  dNoMannerEndDate
	  FROM tCharacterSingleOption 
	 WHERE nCharNo = @nCharNo 		
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_initIDGroupCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 檜  葷 : usp_Character_initIDGroupCount
' 濛撩濠 : Ko Dong Gyun(kodong@gmail.com)
' 濛撩橾 : 2010.11.9
'   檣蝶欐蝶湍瞪 斜瑜滌 霤陛 熱蒂 衙橾 1 蟾晦
' Parameter :
'	input Parameter
'		@nCharNo  : 議葛攪廓
'		@sIDGroup : 檣蝶欐蝶湍瞪 斜瑜
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3191 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_initIDGroupCount]
	@nRet     int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	TRUNCATE TABLE dbo.tInstanceDungeonCount
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_initKeyMap]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_initKeyMap
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.09.13
' Description :
'   캐릭터의 단축키를 저장한다.
'	클라이언트에서 변경된 단축키만 보내오기로 함.
'	데이터베이스에서는 변경된 값을 체크하지 않음(성능상 이슈는 없음)
' Parameter :
'	input Parameter
'		@nCharNo      : 캐릭터번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3092 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_initKeyMap]
	@nCharNo      int
,	@nRet         int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	SET @nRet = 0

	IF EXISTS(SELECT nCharNo FROM tCharacterKeyMap WHERE nCharNo = @nCharNo) BEGIN
		BEGIN TRAN
		
		DELETE FROM tCharacterKeyMap WHERE nCharNo = @nCharNo
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -2723
			ROLLBACK TRAN
			RETURN
		END
		
		INSERT INTO tCharacterKeyMap (nCharNo, nFunctionNo, sys_create_date, nExtendedKey, nASCIICode)
		SELECT @nCharNo, nFunctionNo, GETDATE(), nExtendedKey, nASCIICode
		  FROM tKeyMapInit
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -2724
			ROLLBACK TRAN
			RETURN
		END
		
		COMMIT TRAN
	END
	ELSE BEGIN
		INSERT INTO tCharacterKeyMap (nCharNo, nFunctionNo, sys_create_date, nExtendedKey, nASCIICode)
		SELECT @nCharNo, nFunctionNo, GETDATE(), nExtendedKey, nASCIICode
		  FROM tKeyMapInit
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -2724
			RETURN
		END
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setAuctionNotice]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setAuctionNotice
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2011.01.14.
' Description :
'   경매장 인벤토리에 물건이나 돈이 도착하면 유저에게 알려주기 위해 설정을 잡는다.
'	유저가 인벤토리를 열면 무조건 초기화 시킨다.
' Parameter :
'	input Parameter
'		@nCharNo : 캐릭터번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3192 : db error (insert)
'				-3193 : db error (update)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setAuctionNotice]
	@nCharNo  int
,	@bAuction bit
,	@nRet     int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	SET @nRet = 0

	IF NOT EXISTS(SELECT nCharNo FROM tCharacterSingleOption WHERE nCharNo = @nCharNo) BEGIN
		INSERT INTO tCharacterSingleOption (nCharNo, bAuction)
		VALUES (@nCharNo, @bAuction)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3192
			RETURN
		END		
	END
	ELSE BEGIN
		UPDATE tCharacterSingleOption 
		   SET bAuction = @bAuction 
		 WHERE nCharNo = @nCharNo
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3193
			RETURN
		END		
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setAutoPick]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setAutoPick
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.10.18.
' Description :
'   자동줍기 옵션 설정값 저장
'	GET의 경우 전체를 억세스하지만 개별 옵션들은 별도로 각각 저장한다.
'	각각의 저장시점이 다르므로 통합하여 한번에 저장하지 않는다.
'	저장 실패시 게임상 로그만 남기고 프로그램은 종료하지 않는다.
' Parameter :
'	input Parameter
'		@nCharNo   : 캐릭터번호
'		@bAutoPick : 자동줍기 설정값(0:false/1:true)
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3092 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setAutoPick]
	@nCharNo   int
,	@bAutoPick bit
,	@nRet      int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	SET @nRet = 0

	IF NOT EXISTS(SELECT nCharNo FROM tCharacterSingleOption WHERE nCharNo = @nCharNo) BEGIN
		INSERT INTO tCharacterSingleOption (nCharNo, bAutoPick)
		VALUES (@nCharNo, @bAutoPick)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3192
			RETURN
		END		
	END
	ELSE BEGIN
		UPDATE tCharacterSingleOption 
		   SET bAutoPick = @bAutoPick 
		 WHERE nCharNo = @nCharNo
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3193
			RETURN
		END		
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setChangeID]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setChangeID
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.7.7.
' Description :
'   캐릭터명을 변경하는 프로시저
'	인간관계 초기화 설정시 친구, 결혼, 길드, 홀리프라미스, 채팅블럭, 길드아카데미
'	정보를 초기화 한다.
' Parameter :
'	input Parameter
'		@nRowNo  : 일련번호
'		@nCharNo : 캐릭터번호
'		@sID     : 변경된 캐릭터명
'		@bInit   : 인간관계 초기화여부
'		@nUserNo : 유저번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3023 : 선택한 캐릭터는 삭제된 캐릭터이거나 존재하지 않는 캐릭터입니다.
'				-3024 : 입력된 유저번호와 실제 유저번호가 일치하지 않습니다.
'				-3025 : 길드마스터는 인간관계 초기화를 할 수 없습니다.
'				-3026 : 캐릭터명 변경 오류입니다. db error (update)
'				-3027 : 친구 정보 삭제 오류입니다.
'				-3028 : 결혼 정보 삭제 오류입니다.
'				-3029 : 홀리프라미스 정보 삭제 오류입니다. 하위관계
'				-3030 : 홀리프라미스 정보 삭제 오류입니다. 상위관계
'				-3031 : 채팅 블록 정보 삭제 오류입니다.
'				-3032 : 길드아카데미 정보의 길드아카데미 마스터 정보 갱신 오류입니다.
'				-3033 : 길드 정보 삭제 오류입니다.
'				-3034 : 길드아카데미 정보 삭제 오류입니다.
'				-3035 : 캐릭터명 변경 서비스 반영여부 갱신 오류입니다.
'				-3039 : 이미 사용중인 캐릭터명입니다.
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setChangeID]
	@nRowNo  int
,	@nCharNo int
,	@sID     nvarchar(16)
,	@bInit   bit
,	@nUserNo int
,	@nRet    int = 0 output
AS
BEGIN
	SET NOCOUNT ON

	SET @nRet = 0
	
	DECLARE @sOldID AS nvarchar(50)
	DECLARE @nDBUserNo AS int
	DECLARE @nGrade AS tinyint
	DECLARE @nMyGuildNo AS int
	
	SELECT @sOldID = T1.sID, @nDBUserNo = T1.nUserNo, @nGrade = nGrade
	  FROM tCharacter T1 LEFT OUTER JOIN tGuildMember T2 ON T1.nCharNo = T2.nCharNo
	 WHERE T1.nCharNo = @nCharNo AND T1.bDeleted = 0
	   AND bDeleted = 0
	IF @sOldID = @sID BEGIN
		SET @nRet = -3039
		RETURN
	END	
	IF @nDBUserNo IS NULL BEGIN
		SET @nRet = -3023
		RETURN
	END
	ELSE BEGIN
		-- mismatch userNo
		IF @nDBUserNo <> @nUserNo BEGIN
			SET @nRet = -3024
			RETURN
		END
		
		-- impossible guildmaster
		IF @nGrade IS NOT NULL AND @nGrade = 0 AND @bInit = 1 BEGIN
			SET @nRet = -3025
			RETURN
		END

		BEGIN TRAN
		
		-- change ID
		IF EXISTS(SELECT nCharNo FROM tCharacter WHERE sID = @sID) BEGIN		
			SET @nRet = -3039
			ROLLBACK TRAN
			RETURN
		END
		ELSE BEGIN
			UPDATE tCharacter
			   SET sID = @sID
			 WHERE nCharNo = @nCharNo
			IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
				SET @nRet = -3026
				ROLLBACK TRAN
				RETURN
			END		
		END
		
		-- init Community
		IF @bInit = 1 BEGIN
			-- delete Friend
			IF EXISTS(SELECT nCharNo FROM tFriend WHERE nCharNo = @nCharNo) BEGIN
				DELETE FROM tFriend WHERE nCharNo = @nCharNo
				IF @@ERROR <> 0 OR @@ROWCOUNT < 1 BEGIN
					SET @nRet = -3027
					ROLLBACK TRAN
					RETURN
				END
			END
			IF EXISTS(SELECT nCharNo FROM tFriend WHERE nFriendCharNo = @nCharNo) BEGIN
				DELETE FROM tFriend WHERE nFriendCharNo = @nCharNo
				IF @@ERROR <> 0 OR @@ROWCOUNT < 1 BEGIN
					SET @nRet = -3027
					ROLLBACK TRAN
					RETURN
				END				
			END
			
			-- delete Marriage
			IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nCharNo = @nCharNo) BEGIN
				DELETE FROM tMarriage WHERE nCharNo = @nCharNo
				IF @@ERROR <> 0 OR @@ROWCOUNT < 1 BEGIN
					SET @nRet = -3028
					ROLLBACK TRAN
					RETURN
				END
			END
			IF EXISTS(SELECT nCharNo FROM tMarriage WHERE nPartnerCharNo = @nCharNo) BEGIN				
				DELETE FROM tMarriage WHERE nPartnerCharNo = @nCharNo
				IF @@ERROR <> 0 OR @@ROWCOUNT < 1 BEGIN
					SET @nRet = -3028
					ROLLBACK TRAN
					RETURN
				END				
			END			

			-- delete HolyPromise me
			IF EXISTS(SELECT nCharNo FROM tHolyPromise WHERE nCharNo = @nCharNo) BEGIN
				DELETE FROM tHolyPromise WHERE nCharNo = @nCharNo
				IF @@ERROR <> 0 OR @@ROWCOUNT < 1 BEGIN
					SET @nRet = -3029
					ROLLBACK TRAN
					RETURN
				END
			END
			
			-- delete HolyPromise up
			IF EXISTS(SELECT nCharNo FROM tHolyPromise WHERE nUpCharNo = @nCharNo) BEGIN
				DELETE FROM tHolyPromise WHERE nUpCharNo = @nCharNo
				IF @@ERROR <> 0 OR @@ROWCOUNT < 1 BEGIN
					SET @nRet = -3030
					ROLLBACK TRAN
					RETURN
				END
			END			
			
			-- delete ChatBlock
			IF EXISTS(SELECT nCharNo FROM tChatBlock WHERE nCharNo = @nCharNo) BEGIN
				DELETE FROM tChatBlock WHERE nCharNo = @nCharNo
				IF @@ERROR <> 0 OR @@ROWCOUNT < 1 BEGIN
					SET @nRet = -3031
					ROLLBACK TRAN
					RETURN
				END
			END			
						
			-- delete GuildAcademyMaster & GuildMember		
			SELECT @nMyGuildNo = nNo FROM tGuildMember WHERE nCharNo = @nCharNo
			IF @nMyGuildNo IS NOT NULL BEGIN
				IF EXISTS(SELECT nNo FROM tGuildAcademy WHERE nNo = @nMyGuildNo AND nMasterCharNo = @nCharNo) BEGIN
					-- reset GuildAcademy Master
					UPDATE tGuildAcademy
					   SET nMasterCharNo = (SELECT TOP 1 nCharNo FROM tGuildMember WHERE nNo = @nMyGuildNo AND nGrade = 0)
					 WHERE nNo = @nMyGuildNo
					IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
						SET @nRet = -3032
						ROLLBACK TRAN
						RETURN
					END						 
				END
				-- delete GuildMember
				DELETE FROM tGuildMember WHERE nCharNo = @nCharNo
				IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
					SET @nRet = -3033
					ROLLBACK TRAN
					RETURN
				END
			END
			
			-- delete GuildAcademyMember
			IF EXISTS(SELECT nCharNo FROM tGuildAcademyMember WHERE nCharNo = @nCharNo) BEGIN
				DELETE FROM tGuildAcademyMember WHERE nCharNo = @nCharNo
				IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
					SET @nRet = -3034
					ROLLBACK TRAN
					RETURN
				END	
			END				
		END

		UPDATE tCharacterChangeID 
		   SET sys_update_date = GETDATE(), bFlag = 1, sOldID = @sOldID, sNewID = @sID
		 WHERE nRowNo = @nRowNo 
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			SET @nRet = -3035
			ROLLBACK TRAN
			RETURN
		END
				
		COMMIT TRAN
	END

	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setChangeIDItemUsed]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setChangeIDItemUsed
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.7.7.
' Description :
'   웹페이지에서 캐릭터명 변경 아이템을 사용하면 호출되는 프로시저
' Parameter :
'	input Parameter
'		@nCharNo : 캐릭터번호
'		@bInit   : 인간관계 초기화여부
'		@nUserNo : 유저번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3022 : 캐릭터명 변경 서비스가 이미 진행중인 캐릭터
'				-3023 : 삭제되거나 존재하지 않는 캐릭터
'				-3025 : 길드마스터는 인간관계 초기화를 할 수 없습니다.
'				-3036 : 아이템 소유자가 아닙니다.
'				-3037 : 아이템 삭제 오류
'				-3038 : 아이템 차감 오류
'				-3092 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setChangeIDItemUsed]
	@nCharNo int
,	@bInit   bit
,	@nUserNo int
,	@nItemKey bigint
,	@nItemOption smallint
,	@nItemLot smallint
,	@nRet    int = 0 output
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @nGrade AS tinyint
	SET @nRet = 0

	-- 아이템 소유자 확인
	EXEC p_Item_IsValidOwner @nItemKey, @nCharNo, @nRet OUTPUT
	IF @nRet <> 0 BEGIN
		SET @nRet = -3036
		RETURN
	END

	-- impossible guildmaster
	SELECT @nGrade = nGrade
	  FROM tCharacter T1 LEFT OUTER JOIN tGuildMember T2 ON T1.nCharNo = T2.nCharNo
	 WHERE T1.nCharNo = @nCharNo AND T1.bDeleted = 0
	   AND bDeleted = 0
	IF @nGrade IS NOT NULL AND @nGrade = 0 AND @bInit = 1 BEGIN
		SET @nRet = -3025
		RETURN
	END	   
	   
	IF EXISTS(SELECT nRowNo FROM tCharacterChangeID WHERE nCharNo = @nCharNo AND bFlag = 0) BEGIN
		SET @nRet = -3022
		RETURN
	END
	ELSE IF EXISTS(SELECT nCharNo FROM tCharacter WHERE nUserNo = @nUserNo AND bDeleted = 0) BEGIN
		BEGIN TRAN
		
		-- 아이템 사용 기록
		INSERT INTO tCharacterChangeID (nUserNo, nCharNo, bInit)
		VALUES (@nUserNo, @nCharNo, @bInit)
		IF @@ERROR <> 0 OR @@IDENTITY = 0 BEGIN
			SET @nRet = -3092
			ROLLBACK TRAN
			RETURN
		END	
		
		-- 아이템 삭제 (사용후 Lot = 0 인 경우)
		IF @nItemLot = 0 BEGIN
			EXEC p_Item_Delete @nItemKey, @nRet OUTPUT
			IF @nRet <> 0 BEGIN
				ROLLBACK TRAN
				SET @nRet = -3037
				RETURN
			END
		END
		-- 아이템 차감하기 (사용후 Lot > 0 인 경우)
		ELSE BEGIN
			EXEC p_Item_SetOption @nItemKey, @nItemOption, @nItemLot, @nRet OUTPUT
			IF @nRet <> 0 BEGIN
				ROLLBACK TRAN
				SET @nRet = -3038
				RETURN
			END
		END
		
		COMMIT TRAN		
	END
	ELSE BEGIN
		SET @nRet = -3023
		RETURN	
	END
	
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setChatBan]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setChatBan
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.12.13.
' Description :
'   운영자가 스패머로 판단하여 채팅을 금지시키면 정해진 일정한 시간을 저장하여 금지시킴
' Parameter :
'	input Parameter
'		@sID	  : 캐릭터아이디
'		@nChatBan : 채팅 금지 시간(분)
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3092 : db error (insert)
'				-3093 : db error (update)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setChatBan]
	@sID       nvarchar(40)
,	@nChatBan  int
,	@nRet      int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	DECLARE @nCharNo AS int
	
	SET @nRet = 0
	
	SELECT @nCharNo = nCharNo FROM tCharacter WHERE sID = @sID AND bDeleted = 0
	IF @nCharNo IS NULL BEGIN
		SET @nRet = -3121
	END
	ELSE BEGIN
		IF NOT EXISTS(SELECT nCharNo FROM tCharacterSingleOption WHERE nCharNo = @nCharNo) BEGIN
			INSERT INTO tCharacterSingleOption (nCharNo, nChatBan)
			VALUES (@nCharNo, @nChatBan)
			IF @@ERROR <> 0 BEGIN
				SET @nRet = -3192
				RETURN
			END		
		END
		ELSE BEGIN
			UPDATE tCharacterSingleOption 
			   SET nChatBan = @nChatBan 
			 WHERE nCharNo = @nCharNo
			IF @@ERROR <> 0 BEGIN
				SET @nRet = -3193
				RETURN
			END		
		END
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setGameOption]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setGameOption
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2011.6.29.
' Description :
'   게임옵션을 저장함.
'	유저의 선택에 따라 변경된 내용이 있을때 해당 게임옵션만 저장함.
' Parameter :
'	input Parameter
'		@nCharNo   : 캐릭터번호
'		@nOptionNo : 게임옵션번호
'		@nValue    : 설정값
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setGameOption]
	@nCharNo   int
,	@nOptionNo smallint	
,	@nValue    tinyint
,	@nRet      int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	IF EXISTS(SELECT nCharNo FROM tCharacterGameOption WHERE nCharNo = @nCharNo AND nOptionNo = @nOptionNo) BEGIN
		UPDATE tCharacterGameOption 
		   SET nValue = @nValue
		 WHERE nCharNo = @nCharNo
		   AND nOptionNo = @nOptionNo 
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			SET @nRet = -2792
			RETURN
		END		   
	END
	ELSE BEGIN
		INSERT INTO tCharacterGameOption (nCharNo, nOptionNo, nValue)
		VALUES (@nCharNo, @nOptionNo, @nValue)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -2792
			RETURN
		END		   		
	END		
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setGameOptionInit]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setGameOptionInit
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2011.6.29.
' Description :
'   게임옵션을 초기화함
' Parameter :
'	input Parameter
'		@nCharNo   : 캐릭터번호
'		@nOptionNo : 게임옵션번호
'		@nValue    : 설정값
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setGameOptionInit]
	@nCharNo   int
,	@nRet      int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0
	
	DELETE FROM tCharacterGameOption WHERE nCharNo = @nCharNo
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setIDGroupCount]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 檜  葷 : usp_Character_setIDGroupCount
' 濛撩濠 : Ko Dong Gyun(kodong@gmail.com)
' 濛撩橾 : 2010.11.9
'   檣蝶欐蝶湍瞪 斜瑜滌 霤陛 熱蒂 1 隸陛
' Parameter :
'	input Parameter
'		@nCharNo  : 議葛攪廓
'		@sIDGroup : 檣蝶欐蝶湍瞪 斜瑜
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3191 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setIDGroupCount]
	@nCharNo  int
,	@sIDGroup nvarchar(50)
,	@nRet     int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000
	
	SET @nRet = 0
	
	BEGIN TRAN
	
	IF EXISTS(SELECT nCharNo FROM tInstanceDungeonCount WHERE nCharNo = @nCharNo) BEGIN
		UPDATE tInstanceDungeonCount 
		   SET nCount = nCount + 1
		 WHERE nCharNo = @nCharNo
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			ROLLBACK TRAN
			SET @nRet = -9999
			RETURN
		END
	END
	ELSE BEGIN
		INSERT INTO tInstanceDungeonCount (nCharNo, sIDGroup, nCount)
		VALUES (@nCharNo, @sIDGroup, 1)
		IF @@ERROR <> 0 BEGIN
			ROLLBACK TRAN
			SET @nRet = -9999
			RETURN
		END
	END	
	
	COMMIT TRAN
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setItemActionCoolTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setItemActionCoolTime
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.08.26.
' Description :
'	존링크 또는 로그아웃시 남은 재사용 대기시간을 저장한다.
'	' 2012.4.26 by kodong
'	' 해당 정보가 있을경우 UPDATE / 없을경우 INSERT 방식으로 변경
' Parameter :
'	input Parameter
'		@nCharNo      : 캐릭터번호
'		@nActionGroup : 아이템 액션 그룹
'		@dEndTime     : 종료시간
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3039 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setItemActionCoolTime]
	@nCharNo      int
,	@nActionGroup smallint
,	@dEndTime     datetime
,	@nRet         int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	
	SET @nRet = 0

	IF EXISTS(SELECT nCharNo FROM tItemActionCoolTime WHERE nCharNo = @nCharNo AND nActionGroup = @nActionGroup) BEGIN
		BEGIN TRAN
		
		UPDATE tItemActionCoolTime
		   SET dEndTime = @dEndTime 
		 WHERE nCharNo = @nCharNo 
		   AND nActionGroup = @nActionGroup
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			SET @nRet = -3291
			ROLLBACK TRAN
			RETURN
		END
		
		COMMIT TRAN
	END
	ELSE BEGIN
		INSERT INTO tItemActionCoolTime (nCharNo, nActionGroup, dEndTime)
		VALUES (@nCharNo, @nActionGroup, @dEndTime)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3291
			RETURN
		END
	END	
	
	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setKeyMap]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setKeyMap
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.08.31
' Description :
'   캐릭터의 단축키를 저장한다.
'	클라이언트에서 변경된 단축키만 보내오기로 함.
'	데이터베이스에서는 변경된 값을 체크하지 않음(성능상 이슈는 없음)
' Parameter :
'	input Parameter
'		@nCharNo      : 캐릭터번호
'		@nFunctionNo  : 기능번호
'		@nExtendedKey : 확장키(Ctrl, Alt, Shift)
'		@nASCIICode   : 실제키
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3092 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setKeyMap]
	@nCharNo      int
,	@nFunctionNo  smallint
,	@nExtendedKey tinyint
,	@nASCIICode   tinyint
,	@nRet         int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	SET @nRet = 0

	BEGIN TRAN
	
	IF EXISTS(SELECT nCharNo FROM tCharacterKeyMap WHERE nCharNo = @nCharNo AND nFunctionNo = @nFunctionNo) BEGIN
		UPDATE tCharacterKeyMap 
		   SET nExtendedKey = @nExtendedKey 
		     , nASCIICode = @nASCIICode 
		 WHERE nCharNo = @nCharNo 
		   AND nFunctionNo = @nFunctionNo 
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			SET @nRet = -2793
			ROLLBACK TRAN
			RETURN
		END
	END
	ELSE BEGIN
		INSERT INTO tCharacterKeyMap (nCharNo, nFunctionNo, nExtendedKey, nASCIICode)
		VALUES (@nCharNo, @nFunctionNo, @nExtendedKey, @nASCIICode)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -2792
			ROLLBACK TRAN
			RETURN
		END
	END
	
	COMMIT TRAN
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setMysteryBolt]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setMysteryBolt
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.10.18.
' Description :
'   미스테리 볼트 UI설정 옵션값을 저장함.
'	GET의 경우 전체를 억세스하지만 개별 옵션들은 별도로 각각 저장한다.
'	각각의 저장시점이 다르므로 통합하여 한번에 저장하지 않는다.
'	저장 실패시 게임상 로그만 남기고 프로그램은 종료하지 않는다.
' Parameter :
'	input Parameter
'		@nCharNo      : 캐릭터번호
'		@bMysteryBolt : 미스테리 볼트 UI 설정값(0:false/1:true)
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3092 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setMysteryBolt]
	@nCharNo      int
,	@bMysteryBolt bit
,	@nRet         int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	SET @nRet = 0

	IF NOT EXISTS(SELECT nCharNo FROM tCharacterSingleOption WHERE nCharNo = @nCharNo) BEGIN
		INSERT INTO tCharacterSingleOption (nCharNo, bMysteryBolt)
		VALUES (@nCharNo, @bMysteryBolt)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3192
			RETURN
		END		
	END
	ELSE BEGIN
		UPDATE tCharacterSingleOption 
		   SET bMysteryBolt = @bMysteryBolt 
		 WHERE nCharNo = @nCharNo
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3193
			RETURN
		END		
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setNoMannerEndDate]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 檜  葷 : usp_Character_setNoMannerEndDate
' 濛撩濠 : Ko Dong Gyun(kodong@gmail.com)
' 濛撩橾 : 2011.11.9.
' Description :
'   韁渾蠡蝶 偃摹寰(衙蘆)縑 評艇 綠衙傘 嶸盪 謙猿衛除 晦煙
' Parameter :
'	input Parameter
'		@nCharNo : 議葛攪廓
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3192 : db error (insert)
'				-3193 : db error (update)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setNoMannerEndDate]
	@nCharNo          int
,	@dNoMannerEndDate datetime
,	@nRet             int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	SET @nRet = 0

	IF NOT EXISTS(SELECT nCharNo FROM tCharacterSingleOption WHERE nCharNo = @nCharNo) BEGIN
		INSERT INTO tCharacterSingleOption (nCharNo, dNoMannerEndDate)
		VALUES (@nCharNo, @dNoMannerEndDate)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3192
			RETURN
		END		
	END
	ELSE BEGIN
		UPDATE tCharacterSingleOption 
		   SET dNoMannerEndDate = @dNoMannerEndDate 
		 WHERE nCharNo = @nCharNo
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3193
			RETURN
		END		
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setRestExpExecTime]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setRestExpExecTime
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.10.18.
' Description :
'   휴식경험치 계산을 위한 마지막 시간 저장
'	GET의 경우 전체를 억세스하지만 개별 옵션들은 별도로 각각 저장한다.
'	각각의 저장시점이 다르므로 통합하여 한번에 저장하지 않는다.
'	저장 실패시 게임상 로그만 남기고 프로그램은 종료하지 않는다.
' Parameter :
'	input Parameter
'		@nCharNo : 캐릭터번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3092 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setRestExpExecTime]
	@nCharNo   int
,	@nRet      int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000 
	
	SET @nRet = 0

	IF NOT EXISTS(SELECT nCharNo FROM tCharacterSingleOption WHERE nCharNo = @nCharNo) BEGIN
		INSERT INTO tCharacterSingleOption (nCharNo)
		VALUES (@nCharNo)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3192
			RETURN
		END		
	END
	ELSE BEGIN
		UPDATE tCharacterSingleOption 
		   SET dRestExpLastExecuteTime = GETDATE() 
		 WHERE nCharNo = @nCharNo
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -3193
			RETURN
		END		
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setShortCut]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setShortCut
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.09.13
' Description :
'   캐릭터의 숏컷데이터를 저장
' Parameter :
'	input Parameter
'		@nCharNo      : 캐릭터번호
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-2721 : not found nCharNo
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setShortCut]
	@nCharNo int,
	@nSlotNo tinyint,
	@nCodeNo smallint,
	@nValue  int,
	@nRet    int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET @nRet = 0
	DECLARE @nCodeType smallint SET @nCodeType = 0
	DECLARE @nDBCharNo int
	DECLARE @nPrevCodeNo smallint SET @nPrevCodeNo = 0
	DECLARE @nPrevValue int SET @nPrevValue = 0

	SELECT @nDBCharNo = nCharNo, @nPrevCodeNo = nCodeNo, @nPrevValue = nValue
	  FROM tCharacterShortCut
	 WHERE nCharNo = @nCharNo 
	   AND nSlotNo = @nSlotNo
	IF @nDBCharNo IS NULL BEGIN
		INSERT INTO tCharacterShortCut (nCharNo, nSlotNo, nCodeType, nCodeNo, nValue)
		VALUES (@nCharNo, @nSlotNo, 1, @nCodeNo, @nValue)
		IF @@ERROR <> 0 BEGIN
			SET @nRet = -2791
		END
	END
	ELSE IF @nPrevCodeNo = @nCodeNo AND @nPrevValue = @nValue BEGIN
		SET @nRet = -2722
	END
	ELSE BEGIN
		UPDATE tCharacterShortCut 
		   SET nCodeNo = @nCodeNo
		     , nValue  = @nValue
		     , sys_update_date = GETDATE()
		 WHERE nCharNo = @nCharNo 
		   AND nSlotNo = @nSlotNo
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			SET @nRet = -2793
		END
	END

	SET NOCOUNT OFF
END


GO
/****** Object:  StoredProcedure [dbo].[usp_Character_setStatPoint]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*--------------------------------------------------------------------------------------
' 이  름 : usp_Character_setStatPoint
' 작성자 : Ko Dong Gyun(kodong@gmail.com)
' 작성일 : 2010.10.21.
' Description :
'   캐릭터의 스탯을 저장한다.
'	유료아이템을 사용하여 기존 스탯보다 적어질 때 해당 유료아이템을 삭제한다.
'	
'	1개의 아이템을 삭제할 때와 여러개의 아이템을 삭제해야 할 때를 구분하여
'	처리함으로서 약간의 성능 향상을 기대할 수 있다.
'	영웅기와 오리지널의 서버에서 처리하는 방식이 다르기 때문
'	영웅기는 한번에 적용되지만 오리지널은 매번 건건히 처리한다.
'
'	성능상 이슈가 있는 커서를 사용할 수 밖에 없는 이유는
'	현재 시스템에서 아이템을 순차적으로 지우는 시스템이 존재하지 않아
'	이슈가 있는 커서를 사용하여 지우는 형태를 선택했다.
' Parameter :
'	input Parameter
'		@nCharNo       : 캐릭터번호
'		@nMaxStatPoint : 최대스탯
'		@nStrength     : 힘
'		@nConstitute   : 체력
'		@nDexterity    : 민첩
'		@nIntelligence : 지능
'		@nMentalPower  : 정신
'		@nItemID       : 아이템아이디
'		@nOptionType   : 아이템옵션
'		@nDeleteCount  : 삭제될 아이템 수
'	output Parameter
'		@nRet	 : check SQL execute(valid/invalid)
'			= 0	 : works ok
'			< 0	 : error
'				-3092 : db error (insert)
'-------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_Character_setStatPoint]
	@nCharNo       int
,	@nMaxStatPoint int
,	@nStrength     tinyint
,	@nConstitute   tinyint
,	@nDexterity    tinyint
,	@nIntelligence tinyint
,	@nMentalPower  tinyint
,	@nItemID       int
,	@nOptionType   smallint
,	@nDeleteCount  int
,	@nRet          int = 0 output
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000
	
	DECLARE @nTotalStat   int
	DECLARE @nDeleteCheck int
	DECLARE @nStr int, @nCon int, @nDex int, @nInt int, @nMen int
	DECLARE @nTotalItemCount int, @nItemKey bigint, @nOptionData bigint, @nItemDeleteRemain int, @nRemainCount int
	
	SET @nRet = 0
	SET @nTotalStat = 0
	SET @nDeleteCheck = 0

	-- invalid nCharNo	
	IF @nCharNo <= 0 BEGIN
		SET @nRet = -1011
		RETURN
	END
	
	-- invalid StatPoint
	IF @nStrength < 0 OR @nConstitute < 0 OR @nDexterity < 0 OR @nIntelligence < 0 OR @nMentalPower < 0 BEGIN
		SET @nRet = -1012
		RETURN
	END
	
	-- have many StatPoint
	SET @nTotalStat = @nStrength + @nConstitute + @nDexterity + @nIntelligence + @nMentalPower
	IF @nMaxStatPoint < @nTotalStat BEGIN
		SET @nRet = -1013
		RETURN
	END
	
	IF EXISTS(SELECT nCharNo FROM tCharacter WHERE nCharNo = @nCharNo AND bDeleted = 0) BEGIN
		SELECT @nStr = nStrength
			,  @nCon = nConstitute 
			,  @nDex = nDexterity 
			,  @nInt = nIntelligence 
			,  @nMen = nMentalPower 
		  FROM tCharacter
		 WHERE nCharNo = @nCharNo
		IF @nStr > @nStrength SET @nDeleteCheck = @nDeleteCheck + (@nStr - @nStrength)
		IF @nCon > @nConstitute SET @nDeleteCheck = @nDeleteCheck + (@nCon - @nConstitute)
		IF @nDex > @nDexterity SET @nDeleteCheck = @nDeleteCheck + (@nDex - @nDexterity)
		IF @nInt > @nIntelligence SET @nDeleteCheck = @nDeleteCheck + (@nInt - @nIntelligence)
		IF @nMen > @nMentalPower SET @nDeleteCheck = @nDeleteCheck + (@nMen - @nMentalPower)
		IF @nDeleteCount <> @nDeleteCheck BEGIN
			SET @nRet = -1021
			RETURN
		END
		
		BEGIN TRAN
		
		UPDATE tCharacter
		   SET nStrength = @nStrength 
		   ,   nConstitute = @nConstitute 
		   ,   nDexterity = @nDexterity 
		   ,   nIntelligence = @nIntelligence 
		   ,   nMentalPower = @nMentalPower 
		 WHERE nCharNo = @nCharNo 
		IF @@ERROR <> 0 OR @@ROWCOUNT <> 1 BEGIN
			SET @nRet = -1093
			ROLLBACK TRAN
			RETURN
		END		 

		IF @nDeleteCount > 0  BEGIN
			IF @nDeleteCount = 1 BEGIN
				SELECT TOP 1 @nItemKey = T1.nItemKey, @nOptionData = T2.nOptionData
				  FROM tItem T1, tItemOptions T2
				 WHERE T1.nItemKey = T2.nItemKey 
				   AND T1.nOwner = @nCharNo
				   AND T1.nStorageType = 9
				   AND T1.nItemID = @nItemID 
				 ORDER BY nStorage ASC
				IF @nOptionData > 1 BEGIN
					SET @nOptionData = @nOptionData - 1
					EXEC p_Item_SetOption @nItemKey, @nOptionType, @nOptionData, @nRet output
					IF @nRet <> 0 BEGIN
						SET @nRet = -1022
						ROLLBACK TRAN
						RETURN						
					END					
				END
				ELSE BEGIN
					EXEC p_Item_Delete @nItemKey, @nRet output
					IF @nRet <> 0 BEGIN
						SET @nRet = -1023
						ROLLBACK TRAN
						RETURN						
					END					
				END
			END
			ELSE BEGIN
				SELECT T1.nItemKey, T1.nStorage, T2.nOptionData
				  INTO #tDeleteItem
				  FROM tItem T1, tItemOptions T2
				 WHERE T1.nItemKey = T2.nItemKey 
				   AND T1.nOwner = @nCharNo
				   AND T1.nStorageType = 9
				   AND T1.nItemID = @nItemID 
				 ORDER BY nStorage ASC 
				
				SELECT @nTotalItemCount = SUM(nOptionData) FROM #tDeleteItem
				IF @nTotalItemCount < @nDeleteCount BEGIN
					SET @nRet = -1024
					ROLLBACK TRAN
					RETURN
				END
				ELSE IF @nTotalItemCount = @nDeleteCount BEGIN
					DELETE FROM tItem WHERE nItemKey IN (SELECT nItemKey FROM #tDeleteItem)
					IF @@ERROR <> 0 BEGIN
						SET @nRet = -1023
						ROLLBACK TRAN
						RETURN
					END				
				END
				ELSE BEGIN
					DECLARE CUR_DELETE CURSOR FORWARD_ONLY
					FOR
						SELECT nItemKey, nOptionData
						  FROM #tDeleteItem
						 ORDER BY nStorage ASC
					OPEN CUR_DELETE
					
					SET @nItemDeleteRemain = @nDeleteCount
					FETCH FROM CUR_DELETE INTO @nItemKey, @nOptionData
					WHILE @@FETCH_STATUS = 0 BEGIN
						IF @nItemDeleteRemain >= @nOptionData BEGIN
							EXEC p_Item_Delete @nItemKey, @nRet output
							IF @nRet <> 0 BEGIN
								SET @nRet = -1023
								ROLLBACK TRAN
								RETURN						
							END
							
							SET @nItemDeleteRemain = @nItemDeleteRemain - @nOptionData
						END
						ELSE BEGIN
							SET @nRemainCount = @nOptionData - @nItemDeleteRemain
							EXEC p_Item_SetOption @nItemKey, @nOptionType, @nRemainCount, @nRet output
							IF @nRet <> 0 BEGIN
								SET @nRet = -1022
								ROLLBACK TRAN
								RETURN						
							END	
												
							SET @nItemDeleteRemain = 0
						END		
						
						IF @nItemDeleteRemain = 0 BEGIN
							BREAK
						END
						
						FETCH FROM CUR_DELETE INTO @nItemKey, @nOptionData			
					END
					
					CLOSE CUR_DELETE
					DEALLOCATE CUR_DELETE
				END
			END
		END
		
		COMMIT TRAN				 		
	END
	ELSE BEGIN
		-- not found nCharNo	
		SET @nRet = -1014
		RETURN
	END
END


GO
/****** Object:  StoredProcedure [dbo].[usp_CharacterLoading]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 프로시져 업데이트 및 추가


CREATE  PROCEDURE [dbo].[usp_CharacterLoading]
/*
char loading save
2009.10 By Luunar
 input:
	see SQL
 output:
	= 0 No Error
	< 0 Error
*/

@nCharNo		int,
@dWorldTime		datetime,
@sLoadingMapName	nvarchar(16),
@nFailType		smallint,
@nLoadingFailCnt		smallint,
@sFromMapName	nvarchar(16),
@nFromZoneIP		nvarchar(16),
@nToZoneIP		nvarchar(16),
@nToZonePort		smallint,
@nSeqNoOutput		int OUTPUT,
@nRet			int OUTPUT

AS
BEGIN

	SET NOCOUNT ON

	DECLARE @nSeqNo int
	SET @nSeqNo       = 0

	BEGIN TRAN

	SELECT TOP 1 @nSeqNo = nSeqNo
	  FROM tCharacterLoading
	 WHERE nCharNo = @nCharNo 
	 ORDER BY nSeqNo DESC

	SET @nSeqNo       = @nSeqNo + 1

	INSERT INTO tCharacterLoading( nCharNo, nSeqNo, dWorldTime, sLoadingMapName, nFailType, nLoadingFailCnt, sFromMapName, nFromZoneIP, nToZoneIP, nToZonePort )
	VALUES (@nCharNo, @nSeqNo, @dWorldTime, @sLoadingMapName, @nFailType, @nLoadingFailCnt, @sFromMapName, @nFromZoneIP, @nToZoneIP, @nToZonePort )
	IF @@ERROR <> 0 BEGIN
		-- 파일 에러처리
		SET @nRet = -1001
		ROLLBACK TRAN
		RETURN
	END

	SET @nSeqNoOutput = @nSeqNo
	SET @nRet = 0
	COMMIT TRAN
END


GO
/****** Object:  StoredProcedure [dbo].[usp_CharacterLoadingDetailInfo]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_CharacterLoadingDetailInfo]
/*
char loading save
2009.10 By Luunar
 input:
	see SQL
 output:
	= 0 No Error
	< 0 Error
*/

@nCharNo		int,
@nSeqNo		int,
@nErrorDataNo		smallint,
@nErrorData		int,
@nRet			int OUTPUT

AS
BEGIN

	SET NOCOUNT ON

	INSERT INTO tCharacterLoadingDetailInfo( nCharNo, nSeqNo, nErrorNo, nErrorData )
	VALUES (@nCharNo, @nSeqNo, @nErrorDataNo, @nErrorData )
	IF @@ERROR <> 0 BEGIN
		-- 파일 에러처리
		SET @nRet = -1001
		RETURN
	END

	SET @nRet = 0
END


GO
/****** Object:  StoredProcedure [dbo].[usp_ChargeItem_Draw]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*---------------------------------------------------------------------------------------
' Name : usp_ChargeItem_Draw
' Description : 인출된 아이템 인출완료 체크
'   - 이 저장프로시저에서 Error 가 발생하면 캐릭터 DB 에서 생성된 아이템을 취소하여야 함
' Creator : Ko Dong Gyun(kodong@empal.com)
' Creat Date : 2006-06-17
' Parameter :
'			input Parameter
'				@ROW_NO	: 창고번호
'				@USER_NO	: 유저번호
'			output Parameter
'				@RET
'					-2 : 창고번에 있는 유저번호와 불일치 하는경우
'					-1 : 이미 인출이 완료된 아이템
'					0 : DB Error
'					1 : Success
---------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_ChargeItem_Draw]
	@ROW_NO INT,
	@USER_NO INT,
	@RET	INT = 0 OUTPUT
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000

	EXEC Account.dbo.usp_Charge_ItemDraw @ROW_NO, @USER_NO, @RET OUTPUT
	
	SET NOCOUNT OFF
	SET LOCK_TIMEOUT -1
END


GO
/****** Object:  StoredProcedure [dbo].[usp_ChargeItem_GetList]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*---------------------------------------------------------------------------------------
' Name : usp_ChargeItem_GetList
' Description : 유저번호에 따른 유저창고 리스트를 가져옴
' Creator : Ko Dong Gyun(kodong@empal.com)
' Creat Date : 2006-06-17
' Parameter :
'			input Parameter
'				@USER_NO	: 유저번호
'			output Parameter
'				recordSet : rowNo, goodsNo, amount, registerDate
---------------------------------------------------------------------------------------*/
CREATE PROCEDURE [dbo].[usp_ChargeItem_GetList]
	@USER_NO INT
AS
BEGIN
	SET NOCOUNT ON
	SET LOCK_TIMEOUT 5000

	EXEC Account.dbo.usp_Charge_ItemSelectList @USER_NO

	SET NOCOUNT OFF
	SET LOCK_TIMEOUT -1
END


GO
/****** Object:  StoredProcedure [dbo].[usp_ChargeItem_UseSkillPowerInitDel]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_ChargeItem_UseSkillPowerInitDel]
/*
Charge item use - clear character all skill power and delete used item
2006.6 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Error clear character all skill power
	        2 = Error delete used charge item
*/
@nCharNo int,
@nDeleteItemKey bigint,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
BEGIN TRAN
-- Clear character all skill power
UPDATE tSkill SET 
	nSkillPowerDemage	= 0,
	nSkillPowerSP		= 0,
	nSkillPowerKeepTime = 0,
	nSkillPowerCoolTime = 0
WHERE nCharNo = @nCharNo
IF @@ERROR <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 1
	RETURN
END
-- Delete used charge item
DECLARE @TempRet int
EXEC p_Item_Delete @nDeleteItemKey, @TempRet OUTPUT
IF @TempRet <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 2
	RETURN
END
-- Done
COMMIT TRAN
SET @nRet = 0
RETURN


GO
/****** Object:  StoredProcedure [dbo].[usp_ChargeItem_UseSkillPowerInitLotChange]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_ChargeItem_UseSkillPowerInitLotChange]
/*
Charge item use - clear character all skill power and use item lot change
2006.6 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Error clear character all skill power
	        2 = Error used charge item change lot
*/
@nCharNo int,
@nChangeItemKey bigint,
@nChangeItemOptionType smallint,
@nChangeItemOptionData bigint,		
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
BEGIN TRAN
-- Clear character all skill power
UPDATE tSkill SET 
	nSkillPowerDemage	= 0,
	nSkillPowerSP		= 0,
	nSkillPowerKeepTime = 0,
	nSkillPowerCoolTime = 0
WHERE nCharNo = @nCharNo
IF @@ERROR <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 1
	RETURN
END
-- Used charge item change lot
DECLARE @TempRet int
EXEC p_Item_SetOption @nChangeItemKey, @nChangeItemOptionType, @nChangeItemOptionData, @TempRet OUTPUT
IF @TempRet <> 0
BEGIN
	ROLLBACK TRAN
	SET @nRet = 2
	RETURN
END
-- Done
COMMIT TRAN
SET @nRet = 0
RETURN


GO
/****** Object:  StoredProcedure [dbo].[usp_ChargeItem_UseStatPointDecDel]    Script Date: 12/20/2015 6:11:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_ChargeItem_UseStatPointDecDel]
/*
Charge item use - Stat point decrement and use item delete
2006.6 By CJC
 input:
	see SQL
 output:
	@nRet	0 = OK
	        1 = Error decrement character stat point.
	        2 = Error delete used charge item
*/
@nCharNo int,
@nStatPointType tinyint,
@nDeleteItemKey bigint,
@nRet tinyint OUTPUT
AS
SET NOCOUNT ON
BEGIN TRAN
-- CHECK Type and Decrement stat-point
DECLARE @nStatPoint tinyint
IF @nStatPointType = 0
BEGIN
	SELECT @nStatPoint = nStrength FROM tCharacter WHERE nCharNo = @nCharNo
	IF @nStatPoint < 1
	BEGIN
		SET @nRet = 1
		RETURN
	END
	
	UPDATE tCharacter	SET nStrength	= nStrength - 1					WHERE nCharNo = @nCharNo AND nStrength > 0
END
IF @nStatPointType = 1
BEGIN
	SELECT @nStatPoint = nConstitute FROM tCharacter WHERE nCharNo = @nCharNo
	IF @nStatPoint < 1
	BEGIN
		SET @nRet = 1
		RETURN
	END
	
	UPDATE tCharacter	SET nConstitute = nConstitute - 1				WHERE nCharNo = @nCharNo AND nConstitute > 0
END
	
IF @nStatPointType = 2
